My problem is that my users keep saying to me that the checkbox "stay logged in" doesn't work for them (cookies are set / they had a look into the browsers current cookies and found them). Now I checked twice my code but I can't find any error. Here is my code:
if(isset($_POST['stay_logged_in']) == '1') {
setcookie("anyusr",$username,time()+(3600*24*30)); //30 days
setcookie("anytoken",$securitytoken,time()+(3600*24*30)); //for checking
}
Are I'm missing something? Or should I add something?
Additional Informations
Checking the sessions:
if(!isset($_SESSION)) { session_start(); }
And later I'm using this to check if session is valid
if ($_SESSION['anyusr'] != $meUser['username'] XOR
$_SESSION['anytoken'] != $meUser['superspecialneverguessedtoken']){
setcookie("anyusr","",time()-31536000);
setcookie("anytoken","",time()-31536000);
session_unset();
session_destroy(); }
And my checkbox is here:
<input type="checkbox" id="stay_logged_in" name="stay_logged_in" value="1">
Thanks for any help.
For all others - here is my working solution:
if ((isset($_COOKIE['anyusr'])) && (isset($_COOKIE['anytoken']))) {
$AnyUser = mysql_real_escape_string($_COOKIE['anyusr']);
$AnyToken = mysql_real_escape_string($_COOKIE['anytoken']);
$CookieUser = ''; // num_rows WHERE $AnyUser AND $AnyToken
if ($CookieUser == 1) {
session_start();
$_SESSION['anyusr'] = $_COOKIE['anyusr'];
$_SESSION['anytoken'] = $_COOKIE['anytoken'];
} else {
session_start();
setcookie("anyusr","",time()-31536000);
setcookie("anytoken","",time()-31536000);
session_unset();
session_destroy();
// Later: Redirect to login
}
}
I wanted to write this as a comment, but have to share it as an answer, because of less rep. So, here we go. In your code, you are checking, if the session is valid. But after 30 mins (or one hour) it gets destroyed by serversettings. So you have to check, if there are cookies set, too. If there is a cookie OR a session, you can check if user is valid. Something like this should help:
if (($_COOKIE['anyusr'] || $_SESSION['anyusr']) && ($_COOKIE['anytoken'] || $_SESSION['anytoken']))
{
// check if user is valid
// if valid, user is logged in
// set your session variables with userdata again
}