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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…