Michael
Michael

Reputation: 37

How to match cookie with token in database?

I have writen the following script. Everything works in my application, except the validation keeps returning to login. But I have read a lot about my issue, and everything seems right, but of course there should be something wrong otherwise it would work properly.

In my case a user logs in, a token is stored in the database and in a cookie. For the creation of the token I use:

bin2hex(openssl_random_pseudo_bytes(16));

What I did next is setup a page that first checks if the cookie token and token in the database match. To be sure I first echo them both and both give the same token. I did it like this:

include 'mydatabase.php'; 
$cookie_name = "My_cookiename";
$result = mysql_query("SELECT * FROM users WHERE token='{$_COOKIE[$cookie_name]}'");
while($row = mysql_fetch_array($result)) {

echo $row['token'];
echo $_COOKIE[$cookie_name];

}

Ok so I am sure at this point the cookie token and database token match. Now I want to compare them with an if/else. And here I am going wrong, because I can't get it to work. What I have now is this:

$result = mysql_query("SELECT * FROM users WHERE token='{$_COOKIE[$cookie_name]}'");
while($row = mysql_fetch_array($result)) {
if ($row['token'] != $_COOKIE[$cookie_name]) { 
header('Location:myloginpage.php'); exit(); } else { // MY PAGE CONTENT IF MATCH }

I think there is something wrong with the line:

if ($row['token'] != $_COOKIE[$cookie_name])

Any help would be great, because I am really stuck at this point.

Upvotes: 3

Views: 966

Answers (2)

SwiftNinjaPro
SwiftNinjaPro

Reputation: 853

I think I just solved it :D I was having the same issue, I took the & sign out of my random token generator. when I surrounded the cookie string with htmlentities() I noticed the & signs were replaced with &amp, because strings usually read & as code. once I removed & from the tokens, it worked. Hope this helps.

Upvotes: 0

MarshallOfSound
MarshallOfSound

Reputation: 2719

As the comments on your question have said you are checking things needlessly. The mysql query itself does the token checking for you

include 'mydatabase.php'; 
$cookie_name = "My_cookiename";
$result = mysql_query("SELECT * FROM users WHERE token='{$_COOKIE[$cookie_name]}'");
if (mysql_num_rows($results) != 1) {
    header('Location:myloginpage.php');
    exit();
}
// Content for your page goes here, no need for an else because of exit

Upvotes: 3

Related Questions