I have a third party script and was wondering how I can check with PHP
if session_start()
has been declared before doing something?
best way work for me! if(session_status() != 1) session_start();
function session_started(){ return !!session_id(); }
I suppose you could use the session_id function :
session_id()
returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).
Or maybe testing whether $_SESSION
is set or not, with isset, might do the trick, as it should not be set when no session has been started -- you just have to hope that nothing assigns anything to $_SESSION
without starting the session first.
As in PHP >= 5.4.0, you have function session_status() that tell you if it have been initialize or not or if it's disabled.
For example you can do:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
You can read more about it in http://www.php.net/manual/en/function.session-status.php
I just wrote a simple function for it.
function isSessionStart ()
{
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
return false;
}
return true;
}
else {
if (session_status() == PHP_SESSION_NONE) {
return false;
}
return true;
}
}
if(isset($_SESSION)) {
// do something
}