1

这是我的问题,我可以说 2 页第 1 页和第 2 页,我需要打开会话并在第 1 页上设置 cookie,该 cookie 将保留 1 小时,并在每次页面刷新时重置。现在第 2 页的故事略有不同,首先第 2 页不应该打开任何会话,而是应该检查在第 1 页上打开的任何会话是否仍然有效,如果仍然有效,那么无论请求是什么都继续进行,并且但是,如果访问第 2 页的访问者直接通过保存的 url 访问页面 2,或者如果在会话 cookie 过期后的任何时间访问第 2 页,则在 cookie 的生命周期内保留,则访问者应重定向到第 1 页。

这是我到目前为止在第 1 页上所做的

<?php
function startSession($time = 3600, $ses = 'MYSES') {
    session_set_cookie_params($time);
    session_name($ses);
    session_start();

    // Reset the expiration time upon page load
    if (isset($_COOKIE[$ses]))
      setcookie($ses, $_COOKIE[$ses], time() + $time, "/");
}
?>

问题是,我不知道该做什么以及如何做其余的事情以及我应该在第 2 页上做什么?

这是我在第 2 页尝试过的,但没有奏效。

<?php
if (!isset($_SESSION));{
$a = session_id();
if(empty($a) and $_SERVER['HTTP_REFERER']);{
    header('location: page1.html');}}
?>

请帮助各位。

4

1 回答 1

1

撇开语法问题不谈,看起来您根本没有使用 $_SESSION,要使用 $_SESSION 您必须在任何输出之前声明 session_start() 。因此,在您的情况下,可能仅使用 Cookie。

第 1 页(page1.php):

<?php
    function extendCookie($time = 3600) {
        setcookie('MYSES', 'dummy var', time() + $time, "/");
    }
    extendCookie(); //extend cookie by 3600 seconds (default)
?>
You are on page 1.<br />
<a href="page2.php">Click to proceed to page 2</a>

第 2 页(page2.php):

<?php
    if (!isset($_COOKIE['MYSES'])){
        header('location: page1.php');
    }
?>
You are on page 2.

如果你想使用会话,这将是方式:

第 1 页(page1.php):

<?php
    session_start();
    function extendSession($time = 3600) {
        $_SESSION['expire_time'] = time() + $time;
    }
    extendSession(7200); //extend session by 7200 seconds
?>
You are on page 1.<br />
<a href="page2.php">Click to proceed to page 2</a>

第 2 页(page2.php):

<?php
    session_start();
    if (!isset($_SESSION) || $_SESSION['expire_time'] < time()){
        session_destroy(); //Optional, destroy the expired session.
        header('location: page1.php');
    }
?>
You are on page 2.
于 2013-03-11T10:39:00.420 回答