如何设置会话的生命周期 [英] How to set lifetime of session

查看:36
本文介绍了如何设置会话的生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 PHP 中设置会话生存期?只要请求存在,我想将其设置为永远.请求是 AJAX.我处理 AJAX 请求的 PHP 代码是:

How to set session lifetime in PHP? I Want to set it to forever as long as the request is exist. The request is AJAX. My PHP code that handle AJAX request is:

// AJAX.php
<?php    
session_start();

$_SESSION['counter'] = $_SESSION['counter'] + 1;

header('Content-type: application/json');    
echo json_encode(array('tick' => $_SESSION['counter']));
?>

和 JavaScript:

and the JavaScript:

$(document).ready(function() {            
function check() {
    getJSON('ajax.php');        
}

function getJSON(url) {                                
    return $.getJSON(
                url,
                function(data) {
                    $("#ticker").html(data.tick);
                }
           );
}

setInterval(function() {
    check();
}, 10000); // Tick every 10 seconds

});

会话总是在 300 秒后重置.

The session always resets after 300 seconds.

推荐答案

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.

这篇关于如何设置会话的生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆