Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

php - Load session_start() only if session does not exist?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...