Set "client" in session

Asked

Viewed 33 times

0

Hello, probably the problem may be more logical, but I have a good time up and I can not solve. I am developing an own "analitycs", so when the user accesses the site, receives a fictitious "name" in the session and is recorded in cookies for 15min, the problem is that when recording the logs, at the first access the system does not send the random name generated in the session, only when you change page (but the first access is already recorded in cookies) or F5, I am saving a copy to cookies. Follow the code below:

session_start();
if(!empty($sessaoSite) && $sessaoSite > 4){
    $SESSION['cliente'] = $sessaoSite;
}else{
    $tamanho = mt_rand(5,9);
    $all_str = "abcdefghijlkmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    $nome = "";
    for ($i = 0;$i <= $tamanho;$i++){
      $nome .= $all_str[mt_rand(0,61)];
    }
    if (!isset($_COOKIE['cliente'])) {
        setcookie('cliente', $nome, time() + 900);
        $SESSION['cliente'] = $_COOKIE["cliente"];
    }
}

$SESSION['cliente'] = $_COOKIE["cliente"];

$sessaoSite = $_COOKIE["cliente"];

By not receiving the name on the first access, it messes up all the information and I can’t compare the time that was on the page, because the first access is with the "client" blank and I can’t group this information.

Explaining the rest of the code that is not here: later I recover it here by javascript, JSON format and post to the file that receives the information (date, time, ip, browser...) in an array and send it to the server. I only pasted the first part, because I believe the problem is there, because if I do an echo of $sessaoSite, also only printa after recovering from cookies in another access.

1 answer

0


Guys, I got it, I changed the code and I declared the session variable there at the beginning and it worked/, follow below the solution, if anyone else goes through it, here’s the tip hehe

session_start();
$SESSION['cliente'] = $_COOKIE["cliente"];

$sessaoSite = $SESSION['cliente'];
if(!empty($sessaoSite) && $sessaoSite > 4){
    $SESSION['cliente'] = $sessaoSite;
    $sessaoSite = $sessaoSite;

}else if($sessaoSite == null){
    $tamanho = mt_rand(5,9);
    $all_str = "abcdefghijlkmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    $nome = "";
    for ($i = 0;$i <= $tamanho;$i++){
      $nome .= $all_str[mt_rand(0,61)];
    }

    if (!isset($_COOKIE['cliente'])) {
        setcookie('cliente', $nome, time() + 900);
        $SESSION['cliente'] = $_COOKIE["cliente"];
        $sessaoSite = $_COOKIE["cliente"];
    }
    $sessaoSite = $nome;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.