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?
Response BASED on @Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
only use openSession()
Recommended way for versions of PHP >= 5.4.0 , PHP 7
Reference: http://www.php.net/manual/en/function.session-status.php
For versions of PHP < 5.4.0
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
Or:
So, prior to PHP 5.4 you should set a global boolean.
For versions of PHP prior to PHP 5.4.0:
Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...
That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.
hope it helps !
Actually, it is now too late to explain it here anyway as its been solved. This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order. The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.