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.