Karim Sawma
Karim Sawma

Reputation: 103

Error reading value from cookie

I made a script using a cookie that has a token. Its job is to let me know if the user is logged in or not but I don't know why it always returns false. I checked my database and every time I log in a new record is created but my PHP file always returns false. I am using local server easy php. The first token dies in 7 days. The second one dies in 3 days .

<?php
include('./classes/DB.php');

function isloggedIn(){

    if(isset($_cookie['SNID'])){
        if(DB::query('SELECT user_id FROM login_tokens WHERE token:=token', array(':token'=>sha1($_cookie['SNID'])))){
            $userid = DB::query('SELECT user_id FROM login_tokens WHERE token:=token', array(':token'=>sha1($_cookie['SNID'])))[0]['user_id'];

            if(isset($_cookie['SNID_2'])){

            return $userid;
            }else{
                $cstrong = True;
                $token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
                DB::query('INSERT INTO login_tokens VALUES(null, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$userid));
                DB:query('DELETE FROM login_tokens WHERE token:=token', array(':token'=>sha1($_cookie['SNID'])));

                setcookie("SNID", $token, time()+60*60*24*7, '/', NULL, NULL, TRUE);
                setcookie("SNID_2", $token, time()+60*60*24*3, '/', NULL, NULL, TRUE);

                return $userid;
            }
        }
    }
    return false;
}

if (isloggedIn()){
    echo 'logged in ';
    echo isloggedIn();

    }else{
        echo 'not logged in ';
    }
?>

Upvotes: 0

Views: 172

Answers (1)

user3875721
user3875721

Reputation:

You have to use the superglobal variable $_COOKIE. And your example uses $_cookie. Variable names are case-sensitive so those are different variables.

$_COOKIE is one of the Predefined Variables in PHP.

Second, you can check your cookies in a browser tab Applications Cookie. In that tab look for the value corresponding to key SNID

Upvotes: 1

Related Questions