My current login script I made with PHP Is working, But when i try to login and uncheck “Remember me” It logs in, But does not set the required cookies, However, If i check the Remember box, It logs in and sets the cookies.
So the issue is, What causes it to happend?
My PHP CODE:
<?php
/* Mysql data */
$MysqlUsername = "root";
$MysqlPassword = "";
$MysqlHostname = "localhost";
$MysqlDatabase = "teamgamersnet";
$Salt = "TGN2012";
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$Remember = $_POST['Remember'];
$Cookie = "TGN";
$IP = $_SERVER['REMOTE_ADDR'];
if (empty($Username) || empty($Password)) { die("Please fill in all the fields"); }
$hash = hash('sha256',strtolower($Username).$Password.$Salt);
$Sql = new mysqli($MysqlHostname, $MysqlUsername, $MysqlPassword, $MysqlDatabase);
if ($Sql->connect_error){ echo $Sql->connect_error; }
$sUser = $Sql->real_escape_string($Username);
$sPass = $Sql->real_escape_string($Password);
$xPass = $Sql->real_escape_string($hash);
$CheckUser = $Sql->query("SELECT * FROM `users` WHERE `Username` = '".$sUser."'");;
if ($CheckUser->num_rows == 0) { header("Location: /?p=Login&wrongusr=true"); die(); }
$xCheckUser = $CheckUser->fetch_array(MYSQLI_ASSOC);
if ($xCheckUser['Activated'] == "false") { header("Location: /?p=Login&activate=true"); die(); }
if(strtolower($Username) == strtolower($xCheckUser['Username'])) {
if($hash == $xCheckUser['Password']) { // Check if password is correct
if(isset($Remember)){ // Set a looong cooke to remember
setcookie ($Cookie."User", htmlspecialchars($Username), time() + 99999999);
setcookie ($Cookie."Pass", $hash, time() + 99999999);
header("Location: /?login=true");
}
else
{ // Set a standard cookie
setcookie ($Cookie."User", htmlspecialchars($Username), time() + 3600);
setcookie ($Cookie."Pass", $hash, time() + 3600);
header("Location: /?login=true");
}
}
else
{
header("Location: /?p=Login&wrongpwd=true"); // Send them to home page
}
}
?>
The answer to your question is not due to PHP itself, but (I think) down to your webserver. A bit of information about cookies and how they are set:
– They are based on a timestamp – more importantly, a timestamp set by the server!
– They will automatically expire based on the said timestamp.
I’d strongly suggest looking closely at the HTTP headers that are being sent by the server and checking the expiration date, as I was not able to reproduce your bug locally, but have had similar in production before.
Go on your page, uncheck remember me, and check headers sent to you by the server. You’ll find something like this:
Set-Cookie:TGNPass=some hash; expires=Sat, 17-Nov-2012 22:27:44 GMT
The expiration date/time is what you are after. Check that it is what you are expecting (i.e. one hour from now), and if not, you’ll need to adjust your server’s timezone settings. This is easily done using http://php.net/manual/en/function.date-default-timezone-set.php .