PHP Sessions Login with remember me [duplicate]

匿名 (未验证) 提交于 2019-12-03 01:49:02

问题:

This question already has an answer here:

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.

回答1:

Small example that I often use

function setSession($username,$password,$cookie=null){     // Other code for login ($_POST[]....)     // $row is result of your sql query     $values = array($username,$this->obscure($password),$row['id']);              $session = implode(",",$values);      // check if cookie is enable for login     if($cookie=='on'){         setcookie("your_cookie_name", $session, time()+60*60*24*100,'/');     } else {         $_SESSION["your_session_name"] = $session;     } } 


回答2:

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.



回答3:

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(); } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!