且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置会话的生命周期

更新时间:2023-01-25 17:29:50

PHP 上的会话使用 Cookie 类型的会话,而在服务器端,会话信息不断被删除.

The sessions on PHP works with a Cookie type session, while on server-side the session information is constantly deleted.

在php中设置时间寿命,你可以使用函数session_set_cookie_params,在 session_start 之前:

For set the time life in php, you can use the function session_set_cookie_params, before the session_start:

session_set_cookie_params(3600,"/");
session_start();

例如,3600 秒为一小时,2 小时为 3600*2 = 7200.

For ex, 3600 seconds is one hour, for 2 hours 3600*2 = 7200.

但它是会话cookie,浏览器可以自己过期,如果你想保存大时间的会话(比如记住登录),你需要在服务器端保存数据,在客户端保存一个标准的cookie.

But it is session cookie, the browser can expire it by itself, if you want to save large time sessions (like remember login), you need to save the data in the server and a standard cookie in the client side.

您可以有一个表会话":

You can have a Table "Sessions":

  • session_id int
  • session_hash varchar(20)
  • session_data 文本

在验证 Cookie 时,您可以保存会话 ID";和哈希"(为了安全)在客户端,您可以将会话的数据保存在服务器端,例如:

And validating a Cookie, you save the "session id" and the "hash" (for security) on client side, and you can save the session's data on the server side, ex:

登录时:

setcookie('sessid', $sessionid, 604800);      // One week or seven days
setcookie('sesshash', $sessionhash, 604800);  // One week or seven days
// And save the session data:
saveSessionData($sessionid, $sessionhash, serialize($_SESSION)); // saveSessionData is your function

如果用户返回:

if (isset($_COOKIE['sessid'])) {
    if (valide_session($_COOKIE['sessid'], $_COOKIE['sesshash'])) {
        $_SESSION = unserialize(get_session_data($_COOKIE['sessid']));
    } else {
        // Dont validate the hash, possible session falsification
    }
}

显然,在发送数据之前保存所有会话/cookie 调用.

Obviously, save all session/cookies calls, before sending data.