I have a PHP file that is sometimes called from a page that has started a session and sometimes from a page that doesn\'t have session started. Therefore when I have s
The only thing you need to do is:
<?php
if(!isset($_SESSION))
{
session_start();
}
?>
This should work for all PHP versions. It determines the PHP version, then checks to see if the session is started based on the PHP version. Then if the session is not started it starts it.
function start_session() {
if(version_compare(phpversion(), "5.4.0") != -1){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
} else {
if(session_id() == '') {
session_start();
}
}
}
Replace session_start();
with:
if (!isset($a)) {
a = False;
if ($a == TRUE) {
session_start();
$a = TRUE;
}
}
@
before a function call suppresses any errors that may be reported during the function call.
Adding a @
before session_start
tells PHP to avoid printing error messages.
For example:
Using session_start()
after you've already printed something to the browser results in an error so PHP will display something like "headers cannot be sent: started at (line 12)", @session_start()
will still fail in this case, but the error message is not printed on screen.
Before including the files or redirecting to new page use the exit()
function, otherwise it will give an error.
This code can be used in all cases:
<?php
if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
session_start();
}
?>
Is this code snippet work for you?
if (!count($_SESSION)>0) {
session_start();
}
Not sure about efficiency of such solution, but this is from working project This is also used if you need to define the default language
/**
* Start session
* Fall back to ukrainian language
*/
function valid_session() {
if(session_id()=='') {
session_start();
$_SESSION['lang']='uk';
$_SESSION['lang_id']=3;
}
return true;
}