I have persistent login in my website so if user checks the “remember me” while login process, set cookies to keep user alive all the times in that browser..
There are two routes to access to any page.. If it’s not ajax request, requests go through index.php but if request is ajax it’s just go through ajax.php.
To handle user request first I check session that whether userid stored or not, if session holds user there is no problem, request will be completed.
But if there is no current user id in session, I checked to cookie for autologin, if i can login user through cookie, force to login automatically with cookie data, and set Session with userid while user doesnt do anything..
Right now to handle it, I do the same process at the top of index.php and ajax.php like this;
class SessionManager
{
private function __construct()
{ ; }
public static function getSessionUser()
{
$user = NULL;
if(isset($_SESSION['user']))
$user = $_SESSION['user'];
else
{
/* Get username from cookie, and login it and set Session with user if it's possible otherwise do nothing Session is empty */
getUserFromCookie();
if(isset($_SESSION['user']))
$user = $_SESSION['user'];
}
return $user;
}
}
In index.php;
$user = SessionManager::getSessionUser();
if(!isset($user))
{
include dirname(__FILE__)."/controllers/login_controller.php";
}
and in ajax.php;
$user = SessionManager::getSessionUser();
if(!isset($user))
{
echo json_encode(array("error" => true, "type" => NOT_ALLOWED, "message" => "User should login"));
}
So it works in all cases (I guess :)) , but what I wondering is what’s the best practice to handle it? Any other ideas?
Here is one example of how to create persistent login with PHP, where the database is used in combination with a cookie, to verify that the cookie is authentic:
http://jeremycook.ca/2010/03/28/creating-a-persistent-login-mechanism/