AlexB
AlexB

Reputation: 2184

php session on page 1 and page 2

Here is my question, I have lets say 2 pages page 1 and page 2, what I need is to open session and set cookie on page 1 that will remain for 1 hour and will be reset on every page refresh. Now the page 2 story is slightly different scenario, first of all page 2 should not open any session, but instead should check if any session that was opened on page 1 is still valid and if it is than proceed further with whatever the request was and remain for the lifetime of the cookie, however, if the visitor who is visiting page 2 either directly via saved url or if page 2 is visited any time after the session cookie is expired than visitor should redirected to page 1.

here is what I have done so far on the page 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, "/");
}
?>

the problem is, I have no idea what to and how to do the rest and what I should have on the page 2?

here is what I have tried on page 2, but it did not work.

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

Please help guys.

Upvotes: 1

Views: 404

Answers (1)

Scott Yang
Scott Yang

Reputation: 2428

Syntax issues aside, it doesn't look like you're using $_SESSION at all, to use $_SESSION you must declare session_start() before any output. So in your case perhaps use Cookies only.

Page 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>

Page 2 (page2.php):

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

If you want to use sessions, this would be the way:

Page 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>

Page 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.

Upvotes: 1

Related Questions