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
session_start();
if(!empty($_SESSION['user']))
{
//code;
}
else
{
header("location:index.php");
}
you can do this, and it's really easy.
if (!isset($_SESSION)) session_start();
Hope it helps :)
Prior to PHP 5.4 there is no reliable way of knowing other than setting a global flag.
Consider:
var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.
Or:
session_id(); // returns empty string
session_start();
session_id(); // returns session hash
session_destroy();
session_id(); // returns empty string, ok, but then
session_id('foo'); // tell php the session id to use
session_id(); // returns 'foo', but no session is active.
So, prior to PHP 5.4 you should set a global boolean.
Check this :
<?php
/**
* @return bool
*/
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// Example
if ( is_session_started() === FALSE ) session_start();
?>
Source http://php.net
PHP 5.4 introduced session_status(), which is more reliable than relying on session_id()
.
Consider the following snippet:
session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false
So, to check whether a session is started, the recommended way in PHP 5.4 is now:
session_status() == PHP_SESSION_ACTIVE
For all php version
if ((function_exists('session_status')
&& session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
session_start();
}