如何在php中设置Session Timeout?

时间:2015-10-29 04:54:14

标签: php session session-cookies logout session-timeout

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

  

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');
?>

我错过了什么吗?这是因为我的会话超时无效。

1 个答案:

答案 0 :(得分:-1)

在页面加载时启动Javascript计时器,并在redirect时将用户logout发送到timer expires页。

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