Skip to content
Advertisement

session_status() returns none on reload

I have already seen this identical opposite question and its OP code sample seems perfectly fine to me. I’ve also read (including PHP docs) that session can be checked with session_status() on PHP >= 5.4 and it should be fine to do so before calling session_start() to determine if it already exists.

Now, I’m using PHP 5.4.16 on a CentOS 7.10 machine and the session_status() always returns 1 (PHP_SESSION_NONE) for me, only when I reload the page with this example:

<?php
$status = session_status();
session_start();
echo "The session status is : $status";

I expect it returns PHP_SESSION_ACTIVE (2) when I reload page (and I’m not forcing-reload with cache clear). I’m using latest Chrome version, and the page is embedded inside a virtual host with HTTPS over port 8443.

I’ve checked the PHP version with both php --version and via phpinfo() script to discard any version conflict just in case, and they’re same. Additionally, when I visit the session script page, the server creates empty files at /var/lib/php/session directory. I didn’t change default PHP settings for session or anything.

To make it clear: the session_status() works fine if checked afterwards on same script execution (The session status is : 2), but naturally I’m not interested in that since I want to check if session exist in first place.

What could be wrong?

Advertisement

Answer

Your session_status will always be PHP_SESSION_NONE until you call session_start in the lifetime of the current request. It does not matter if on some previous request you “already started” a session: you need to “re-start” it, to resume a previously started session. This is done via cookies.

If your intent is to start a session only if the user already did something in the past that started a session (eg. they already logged in previously) and you want to resume a session but not start a new one, then you could simply check if (isset($_COOKIE['PHPSESSID'])).

This may be beneficial if you know most of your users won’t need a session, and you want to avoid cookies and the overhead involved with a session, but still be able to handle the cases when a session is needed.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement