Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...