is there a short code trick to check if a session has started and if not then load one? Currently I receive an error "session already started..." if I put in a session start regardless of checking.
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie. When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers.
In ancient history you simply needed to check session_id() . If it's an empty string, then session is not started. Otherwise it is.
You can use the session_status() function, a better option as it accounts for sessions being disabled and checks if a session already exists.
isset
is generally the proper way to check if predefined variables are currently defined:
If you are using a version of php prior to 5.4,
you can usually get away with and its tempting just doing the code below, but be aware that if for some reason sessions are disabled, session_start() will still be called which could end up leading to errors and needless debugging since the $_SESSION array isn't allowed to be created.
if(!isset($_SESSION)){session_start();}
if you want to account for checking to see if sessions are disabled for some reason, you can supress the error message, set a test session variable, and then verify it was set. If its not, you can code in a reaction for disabled sessions. You'll want to do all this at or near the start of your script. So as an example(works differently depending on error handling setting):
if(!isset($_SESSION)){session_start();}
$_SESSION['valid'] = 'valid';
if($_SESSION['valid'] != 'valid')
{
//handle disabled sessions
}
However, if you are using php version 5.4 or greater,
You can use the session_status() function, a better option as it accounts for sessions being disabled and checks if a session already exists.
if (session_status() === PHP_SESSION_NONE){session_start();}
NOTE that PHP_SESSION_NONE is a constant set by PHP and therefore does not need to be wrapped in quotes. It evaluates to integer 1, but as its a constant that was specifically set to eliminate the need for magic numbers, best to test against the constant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With