I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn't have session started. Therefore when I have session_start()
on this script I sometimes get the error message for "session already started". For that I've put these lines:
if(!isset($_COOKIE["PHPSESSID"]))
{
session_start();
}
but this time I got this warning message:
Notice: Undefined variable: _SESSION
Is there a better way to check if session has already started?
If I use @session_start
will it make things work properly and just shut up the warnings?
PHP 5.4 introduced session_status(), which is more reliable than relying on
session_id()
.Consider the following snippet:
So, to check whether a session is started, the recommended way in PHP 5.4 is now:
you can do this, and it's really easy.
Hope it helps :)
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
Not sure about efficiency of such solution, but this is from working project This is also used if you need to define the default language
PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it.
session_status
is available as of PHP 5.4 , so we have to check this too:Is this code snippet work for you?