简体   繁体   English

PHP 如何让用户保持登录状态,直到他们注销?

[英]PHP how to keep user logged until they log out?

I'd like to know how to keep the user logged in indefinitely, until they click the logout button.我想知道如何让用户无限期地登录,直到他们点击注销按钮。 Currently I have a session variable loggedin that checks whether the user is logged in, but session variables expire after some time.目前我有一个 session 变量已loggedin ,用于检查用户是否已登录,但 session 变量会在一段时间后过期。 How do I keep the user logged in indefinitely?如何让用户无限期登录?

You can use a cookie for this.您可以为此使用 cookie。 When the user logging in for the first time, set a cookie for maybe 10 years.当用户第一次登录时,设置一个可能 10 年的 cookie。 Then, when the user navigates the pages, update/reset the cookie to a further 10 years.然后,当用户浏览页面时,将 cookie 更新/重置为 10 年。

setcookie(
  "CookieName",
  "CookieValue",
  time() + (10 * 365 * 24 * 60 * 60)
);

Setting a Cookie in PHP在 PHP 中设置 Cookie

And when the user comes back to the site after some time, check if the cookie is available.当用户在一段时间后返回网站时,检查 cookie 是否可用。 If available, you can log them in automatically, if not, redirect to the login page.如果可用,您可以自动登录,如果没有,则重定向到登录页面。

if(isset($_COOKIE['CookieName'])){
    $cookie = $_COOKIE['CookieName'];
}
else{
    // No Cookie found - Redirect to Login
}

You can use two cookies for user name and password(encrypted).您可以使用两个 cookies 作为用户名和密码(加密)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM