如何在 php 中设置会话超时?

How to set Session Timeout in php?

我在 PHP 语言方面还是新手,正在尝试如何设置会话超时,以确保当用户登录他们的帐户时,它会限制在帐户前几分钟/1 小时当用户登录时间过长时自动注销。我参考了这个 link.

http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions

index.php

<?php
if(!isset($_SESSION))
{ 
  session_start(); 
}

$timeout = $_SERVER['REQUEST_TIME'];
/**
 * for a 1 minute timeout, specified in seconds
*/
$timeout_duration = 60;

if (isset($_SESSION['LAST_ACTIVITY']) && ($timeout - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    session_start();
}

$_SESSION['LAST_ACTIVITY'] = $timeout;
?>

coupon.php

<?php 
// error_reporting(E_ALL); ini_set("display_errors", 1);
session_start();
$timeout = 60; // Number of seconds until it times out.

// Check if the timeout field exists.
if(isset($_SESSION['timeout'])) {
    $duration = time() - (int)$_SESSION['timeout'];
    if($duration > $timeout) {
        // Destroy the session and restart it.
        session_destroy();
    }
}

// Update the timeout field with the current time.
$_SESSION['timeout'] = time();
// include ('sessionTimeout.php');

if( !isset($_SESSION["loginSuccess"]) ){
    echo "<script type='text/javascript'>alert('Login failed!');</script>";
    die('<meta http-equiv="refresh" content="0;URL=\'login-redirect.php\'" />');
}
?>

sessionTimeout.php

<?php
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
    // Set the max lifetime
    ini_set("session.gc_maxlifetime", $timeout);

    // Set the session cookie to timout
    ini_set("session.cookie_lifetime", $timeout);

    $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\" : "/";
    $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
    if(!file_exists($path)) {
        if(!mkdir($path, 600)) {
            trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
        }
    }
    ini_set("session.save_path", $path);

    // Set the chance to trigger the garbage collection.
    ini_set("session.gc_probability", $probability);
    ini_set("session.gc_divisor", 100); // Should always be 100

    // Start the session!
    session_start_timeout(60, 10);

    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
    }
}

?>

logout.php

<?php 
session_start();

include('config.php');

foreach($_SESSION as $key => $value){
    if (strpos($key, $PROJECT_NAME) !== FALSE){
        unset($_SESSION[$key]);
    }
}

$_SESSION[$PROJECT_NAME . 'logout'] = true;
session_destroy();

//print_r($_SESSION);
header('Location:' . $base_url . 'index');
?>

我是不是漏掉了什么?这是因为我的会话超时不起作用。

在页面加载时启动 Javascript 计时器,并在 timer expiresredirect 用户转到 logout 页面。

<script type="text/javascript">
setTimeout(function() { window.location.href = "logout.php"; }, 60 * 60 * 1000);
</script>