Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sessions Login with remember me [duplicate]

Ive got a PHP Registration/Login system using PHP Sessions which is working perfectly, I want the user to be able to tick remember me and then they stay logged in forever or at least a week or something.

Im guessing I need to store a cookie and check, I was confused at what I actually need to store in the cookie. If I store the userid or username then can't someone just use a fake cookie to look at another users data?

Any advance is appreciated.

like image 665
Exoon Avatar asked Aug 23 '12 12:08

Exoon


2 Answers

All you need to do is extend the PHP session cookie. The following example extends the cookie by 30 days:

$params = session_get_cookie_params();
setcookie(session_name(), $_COOKIE[session_name()], time() + 60*60*24*30, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);

I think by your security question you are just concerned about putting values which can be easily hacked. PHP session cookies have a random value and store its contents on the file system so you should be fine.

like image 156
Luke Avatar answered Nov 17 '22 14:11

Luke


After successful login do:

$_SESSION['user_is_loggedin'] = 1;

$cookiehash = md5(sha1(username . user_ip));
setcookie("uname",$cookiehash,time()+3600*24*365,'/','.yoursite.com');

store in sql:

$sql = "UPDATE `users` SET `login_session`='$cookiehash' WHERE `user_id`='$uid'";

to check if user logged in:

function CheckCookieLogin() {
    $uname = $_COOKIE['uname']; 
    if (!empty($uname)) {   
        $sql = "SELECT * FROM `users` WHERE `login_session`='$uname'";
        $_SESSION['user_is_loggedin'] = 1;
        $_SESSION['cookie'] = $uname;
        // reset expiry date
        setcookie("uname",$uname,time()+3600*24*365,'/','.yoursite.com');
    }
}

if(!isset($_SESSION['cookie']) && empty($_SESSION['user_is_loggedin'])) {
    CheckCookieLogin();
}
like image 30
Ghassan Elias Avatar answered Nov 17 '22 14:11

Ghassan Elias