我有一个PHP文件,有时从一个已经开始会话的页面调用,有时从一个没有会话启动的页面调用。因此,当我在这个脚本上有session_start()时,我有时会得到“会话已经开始”的错误消息。为此,我写了以下几行:
if(!isset($_COOKIE["PHPSESSID"]))
{
session_start();
}
但这次我收到了警告信息:
注意:未定义变量:_SESSION
是否有更好的方法来检查会话是否已经开始?
如果我使用@session_start,它会使事情正常工作,只是关闭警告?
PHP 5.4引入了session_status(),它比依赖session_id()更可靠。
考虑下面的代码片段:
session_id('test');
var_export(session_id() != ''); // true, but session is still not started!
var_export(session_status() == PHP_SESSION_ACTIVE); // false
因此,要检查会话是否已启动,PHP 5.4中推荐的方法是:
session_status() == PHP_SESSION_ACTIVE
推荐的方法为版本的PHP >= 5.4.0, PHP 7, PHP 8
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
参考:http://www.php.net/manual/en/function.session-status.php
适用于PHP < 5.4.0版本
if(session_id() == '') {
session_start();
}
基于@Meliza Ramos的回复(见第一个回复)和http://php.net/manual/en/function.phpversion.php,
行动:
如果不存在,定义PHP_VERSION_ID
根据PHP_VERSION_ID定义函数检查版本
定义函数为openSession()安全
只使用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();
}
}