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
PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it.
session_status
is available as of PHP 5.4 , so we have to check this too:
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
$version = PHP_VERSION_ID;
}
if($version < 50400){
if(session_id() == '') {
session_start();
}
}else{
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
}
Based on my practice, before accessing the $_SESSION[]
you need to call session_start
every time to use the script. See the link below for manual.
http://php.net/manual/en/function.session-start.php
For me at least session_start
is confusing as a name. A session_load
can be more clear.
if (version_compare(phpversion(), '5.4.0', '<')) {
if(session_id() == '') {
session_start();
}
}
else
{
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
Response BASED on @Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,
ACTIONS:
only use openSession()
// PHP_VERSION_ID is available as of PHP 5.2.7, if our
// version is lower than that, then emulate it
if (!defined('PHP_VERSION_ID')) {
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
// PHP_VERSION_ID is defined as a number, where the higher the number
// is, the newer a PHP version is used. It's defined as used in the above
// expression:
//
// $version_id = $major_version * 10000 + $minor_version * 100 + $release_version;
//
// Now with PHP_VERSION_ID we can check for features this PHP version
// may have, this doesn't require to use version_compare() everytime
// you check if the current PHP version may not support a feature.
//
// For example, we may here define the PHP_VERSION_* constants thats
// not available in versions prior to 5.2.7
if (PHP_VERSION_ID < 50207) {
define('PHP_MAJOR_VERSION', $version[0]);
define('PHP_MINOR_VERSION', $version[1]);
define('PHP_RELEASE_VERSION', $version[2]);
// and so on, ...
}
}
function phpVersionAtLeast($strVersion = '0.0.0')
{
$version = explode('.', $strVersion);
$questionVer = $version[0] * 10000 + $version[1] * 100 + $version[2];
if(PHP_VERSION_ID >= $questionVer)
return true;
else
return false;
}
function openSession()
{
if(phpVersionAtLeast('5.4.0'))
{
if(session_status()==PHP_SESSION_NONE)
session_start();
}
else // under 5.4.0
{
if(session_id() == '')
session_start();
}
}
i ended up with double check of status. php 5.4+
if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};
You should reorganize your code so that you call session_start()
exactly once per page execution.