2015-10-29 3 views
0

Я все еще новичок в языке PHP. Я хотел бы установить время ожидания сеанса, чтобы гарантировать, что когда пользователь войдет в свою учетную запись, он будет ограничен до нескольких минут/за 1 час до того, как учетная запись автоматически выйдет из системы, когда пользователь войдет в систему слишком долго. Я refered по этой ссылкеНастройка тайм-аута сеанса PHP

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

при настройке. Возможно, я не знаю, как это работает, правильно ли я разместил код. Но я надеюсь, что кто-то проведет меня через этот вопрос.

Я тестирую, просто размещая тайм-аут сеанса на одной из страниц. Сессия заканчивается через 1 минуту.

coupon.php

<?php 
session_start(); 
$timeout = 60; // Number of seconds until it times out. 

// Check if the timeout field exists. 
if(isset($_SESSION['timeout'])) { 
    // See if the number of seconds since the last 
    // visit is larger than the timeout period. 
    $duration = time() - (int)$_SESSION['timeout']; 
    if($duration > $timeout) { 
     // Destroy the session and restart it. 
     session_destroy(); 
     session_start(); 
    } 
} 

// Update the timeout field with the current time. 
$_SESSION['timeout'] = time(); 
?> 

sessionTimeout.php

<?php 
/*** 
* Starts a session with a specific timeout and a specific GC probability. 
* @param int $timeout The number of seconds until it should time out. 
* @param int $probability The probablity, in int percentage, that the garbage 
*  collection routine will be triggered right now. 
* @param strint $cookie_domain The domain path for the cookie. 
*/ 
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); 

    // Change the save path. Sessions stored in teh same path 
    // all share the same lifetime; the lowest lifetime will be 
    // used for all. Therefore, for this to work, the session 
    // must be stored in a directory where only sessions sharing 
    // it's lifetime are. Best to just dynamically create on. 
    $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); 

    // Renew the time left until this session times out. 
    // If you skip this, the session will time out based 
    // on the time when it was created, rather than when 
    // it was last used. 
    if(isset($_COOKIE[session_name()])) { 
     setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain); 
    } 
} 

?> 

index.php

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

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

/** 
* Here we look for the user’s LAST_ACTIVITY timestamp. If 
* it’s set and indicates our $timeout_duration has passed, 
* blow away any previous $_SESSION data and start a new one. 
*/ 
if (isset($_SESSION[‘LAST_ACTIVITY’]) && ($timeout - $_SESSION[‘LAST_ACTIVITY’]) > $timeout_duration) { 
    session_unset(); 
    session_destroy(); 
    session_start(); 
} 

/** 
* Finally, update LAST_ACTIVITY so that our timeout 
* is based on it and not the user’s login time. 
*/ 
$_SESSION[‘LAST_ACTIVITY’] = $timeout; 
?> 
+1

Почему вы используете * умные * кавычки? – Script47

+0

Что значит? @ Script47 –

+0

Посмотрите ответ @ Fred-ii-s ниже. – Script47

ответ

2

У вас есть целая куча фанковых цитат в вашем коде, и это приведет к сбою.

т.е .:

$_SERVER[‘REQUEST_TIME’]; 
     ^  ^

те должны быть регулярными/стандартные кавычки.

$_SERVER['REQUEST_TIME']; 

Внесите эти изменения в остальную часть.

Использование отчетов об ошибках должно было бы сигнализировать уведомления.

Вы можете легко найти и заменить тех, кто один раз в редакторе кода или даже Блокнот с CTRL-H

+1

Arggggggggg пират Фреда знает –

+1

* Arrrrrr дружище! * @Dagon –

+0

* Вы забыли одну очень важную вещь, помощник, я капитан Джек Воробей. * – Script47

Смежные вопросы