I have a third party script and was wondering how I can check with PHP
if session_start()
has been declared before doing something?
something like if(isset($_session_start())) { //do something }
I have a third party script and was wondering how I can check with PHP
if session_start()
has been declared before doing something?
something like if(isset($_session_start())) { //do something }
if(!isset($_SESSION)) {
session_start();
}
The check will allow you to keep your current session active even if it's a loop back submission application where you plan to reuse the form if data is typed incorrectly or have additional checks and balances within your program before proceeding to the next program.
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 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.
for php >= 5.4.0
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
for php < 5.4.0
if(session_id() == '') {
session_start();
}
function session_started(){ return !!session_id(); }
If session already started, Error: "Fatal error: Can't use function return value in write context"
Try this:
$session = session_id();
if(empty($session)){
session_start();
}
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;
}
}