Set "client" in session

0

Hello, probably the problem may be more logical, but I've been a long time and I can not solve it. I'm developing an "analitycs" itself, so when the user accesses the site, he receives a fictitious "name" in the session and is recorded in the cookies for 15min, the problem is that when he writes the logs, at the first access the system does not send the name randomly generated session, only when the page changes (but the first access is already saved in the cookies) or F5, I am writing a copy in the cookies. Here is the code:

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"];

Because I do not receive the name on the first access, it messes up all the information and I can not compare the time it was on the page, because the first access is left with the "client" blank and I can not gather this information.

Explaining the rest of the code that is not here: later I retrieve this here by javascript, format in JSON and make a post for the file that receives the information (date, time, ip, browser ...) in an array and send to server. I've just pasted the first part, because I believe the problem is there, why do I echo the $ sessionSao, also only printa after it recovers from cookies in another access.

    
asked by anonymous 21.03.2017 / 18:30

1 answer

0

Well, I did it, I changed the code and declared the session variable at the beginning and it worked fine, the solution goes down, if anyone else goes through it, there'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;
}
    
21.03.2017 / 19:00