Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session disappear after page refresh

Tags:

php

session

This is the first time that I'm using sessions on PHP. Getting some info from StackOverflow and other websites I'm into to build my first PHP Login but I'm getting a problem and don't know how to resolve it.

Basically at the moment that I set a session, after the page refresh, this session disappear. Is not supposed to remain for an amount of time? (that can be set with set_cookie_params etc, but this is another topic)

I have at the beginning of my page (global) this code:

ini_set('session.cookie_httponly', 1);
ini_set('session.entropy_file', '/dev/urandom');
ini_set('session.hash_function', 'whirlpool');
ini_set('session.use_only_cookies', 1);
ini_set('session.cookie_secure', 1);

session_name("RANDOMID");
session_start();

if (isset($_SESSION['uid']))
{
    if ($_SESSION['ipremote'] !== getUserIP() && $_SESSION['useragent'] !== getUserAgent())
    {
        session_unset();
        session_destroy();

        session_regenerate_id(true);
    }
}
else
{
    session_regenerate_id(true);

    $_SESSION['ipremote'] = getUserIP();
    $_SESSION['useragent'] = getUserAgent();
}

then in my login.php file, when the user insert the right infos:

$_SESSION['uid'] = 3;

header("Location: index.php");
exit;

The problem that after the redirect the uid session disappear: I put at the end of the index.php page a var_dump of the $_SESSION variable, and I see just the IP and user-agent that is set everytime in the else condition.

EDIT: I tried to replace all the content of the session initialization with just session_start(); and it works, I don't understand why this secure session initialization it doesn't working and making the session disappear.

like image 539
Keaire Avatar asked Jan 30 '18 09:01

Keaire


1 Answers

Are you calling your page via https:// when you are testing this ...?

Otherwise, the explanation is simple:

ini_set('session.cookie_secure', 1);

This makes PHP set the session cookie with the secure flag, meaning the browser is only allowed to send this cookie back with requests made over a secure connection.

So if you are actually testing this via HTTP only, then the session cookie will not be send back with the next request, so PHP does not find any session id, and therefor starts a fresh, new session when you call session_start ...

like image 78
CBroe Avatar answered Sep 26 '22 03:09

CBroe