检查 PHP 会话是否已经启动

发布于 2024-11-14 04:17:36 字数 357 浏览 4 评论 0原文

我有一个 PHP 文件,有时从已启动会话的页面调用,有时从未启动会话的页面调用。因此,当我在此脚本上使用 session_start() 时,有时会收到“会话已启动”的错误消息。为此,我添加了以下几行:

if(!isset($_COOKIE["PHPSESSID"]))
{
  session_start();
}

但这次我收到了此警告消息:

注意:未定义的变量:_SESSION

有没有更好的方法来检查会话是否已经开始?

如果我使用 @session_start 会让事情正常工作并关闭警告吗?

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 session_start() on this script I sometimes get the error message for "session already started". For that I've put these lines:

if(!isset($_COOKIE["PHPSESSID"]))
{
  session_start();
}

but this time I got this warning message:

Notice: Undefined variable: _SESSION

Is there a better way to check if session has already started?

If I use @session_start will it make things work properly and just shut up the warnings?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(28

贪了杯 2024-11-21 04:17:36

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();
}

Recommended way for versions of PHP >= 5.4.0 , PHP 7, PHP 8

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Reference: http://www.php.net/manual/en/function.session-status.php

For versions of PHP < 5.4.0

if(session_id() == '') {
    session_start();
}
浪漫之都 2024-11-21 04:17:36

对于 PHP 5.4.0 之前的 PHP 版本:

if(session_id() == '') {
    // session isn't started
}

不过,恕我直言,如果您不知道会话是否已启动,您确实应该考虑重构会话管理代码...

也就是说,我的意见是主观的,并且在某些情况下(下面的评论中描述了示例)可能无法知道会话是否已启动。

For versions of PHP prior to PHP 5.4.0:

if(session_id() == '') {
    // session isn't started
}

Though, IMHO, you should really think about refactoring your session management code if you don't know whether or not a session is started...

That said, my opinion is subjective, and there are situations (examples of which are described in the comments below) where it may not be possible to know if the session is started.

我为君王 2024-11-21 04:17:36

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 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
[旋木] 2024-11-21 04:17:36

你可以做到这一点,而且非常简单。

if (!isset($_SESSION)) session_start();

you can do this, and it's really easy.

if (!isset($_SESSION)) session_start();
清风无影 2024-11-21 04:17:36
if (version_compare(phpversion(), '5.4.0', '<')) {
     if(session_id() == '') {
        session_start();
     }
 }
 else
 {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
 }
if (version_compare(phpversion(), '5.4.0', '<')) {
     if(session_id() == '') {
        session_start();
     }
 }
 else
 {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
 }
星星的轨迹 2024-11-21 04:17:36

在 PHP 5.4 之前,除了设置全局标志之外,没有可靠的方法来了解。

考虑:

var_dump($_SESSION); // null
session_start();
var_dump($_SESSION); // array
session_destroy();
var_dump($_SESSION); // array, but session isn't active.

或者:

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.

因此,在 PHP 5.4 之前,您应该设置一个全局布尔值。

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.

久随 2024-11-21 04:17:36

适用于所有 php 版本

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}

For all php version

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}
宛菡 2024-11-21 04:17:36

检查这个:

<?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();
?>

来源 http://php.net

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

草莓酥 2024-11-21 04:17:36

使用 session_id(),如果未设置则返回空字符串。它比检查 $_COOKIE 更可靠。

if (strlen(session_id()) < 1) {
    session_start();
}

Use session_id(), it returns an empty string if not set. It's more reliable than checking the $_COOKIE.

if (strlen(session_id()) < 1) {
    session_start();
}
猥琐帝 2024-11-21 04:17:36
if (session_id() === "") { session_start(); }

希望有帮助!

if (session_id() === "") { session_start(); }

hope it helps !

留一抹残留的笑 2024-11-21 04:17:36

这应该适用于所有 PHP 版本。它确定 PHP 版本,然后检查会话是否根据 PHP 版本启动。然后,如果会话未启动,它将启动它。

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();
    }
  }
}

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();
    }
  }
}
夏尔 2024-11-21 04:17:36

您唯一需要做的就是:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>

The only thing you need to do is:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>
仙女山的月亮 2024-11-21 04:17:36

不确定此类解决方案的效率,但这是来自工作项目
如果您需要定义默认语言,也可以使用此方法

   /**
    * Start session
    * Fall back to ukrainian language
    */
   function valid_session() {
    if(session_id()=='') {
        session_start();
        $_SESSION['lang']='uk';
        $_SESSION['lang_id']=3;
    }
    return true;
  }

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;
  }
水晶透心 2024-11-21 04:17:36

函数调用之前的 @ 会抑制函数调用期间可能报告的任何错误。

session_start 之前添加 @ 告诉 PHP 避免打印错误消息。

例如:

在将某些内容打印到浏览器后使用 session_start() 会导致错误,因此 PHP 将显示类似“无法发送标头:从(第 12 行)开始”的内容,@session_start() 仍然会失败,但错误消息不会打印在屏幕上。

在包含文件或重定向到新页面之前,请使用 exit() 函数,否则会出错。

此代码可用于所有情况:


    <?php 
        if (session_status() !== PHP_SESSION_ACTIVE || session_id() === ""){
            session_start(); 
        }
    ?>

@ 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(); 
        }
    ?>

蒗幽 2024-11-21 04:17:36

在 PHP 5.3 上,这对我有用:

if(!strlen(session_id())){
    session_name('someSpecialName');
    session_start();
} 

那么你就可以了。如果您不将 not 放在 if 语句开始,会话将以任何方式启动,我不知道为什么。

On PHP 5.3 this works for me:

if(!strlen(session_id())){
    session_name('someSpecialName');
    session_start();
} 

then you have. If you do not put the not at if statement beginning the session will start any way I do not why.

阳光①夏 2024-11-21 04:17:36

基于 @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();
        }
    }

Response BASED on @Meliza Ramos Response(see first response) and http://php.net/manual/en/function.phpversion.php ,

ACTIONS:

  • define PHP_VERSION_ID if not exist
  • define function to check version based on PHP_VERSION_ID
  • define function to openSession() secure

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();
        }
    }
南冥有猫 2024-11-21 04:17:36
if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
    $sess = session_status();
    if ($sess == PHP_SESSION_NONE) {
        session_start();
    }
} else {
    if (!$_SESSION) {
        session_start();
    }
}

事实上,现在无论如何都已经晚了,因为它已经解决了。
这是我的一个项目的 .inc 文件,您可以通过选择菜肴并删除/添加或更改订单来配置餐厅的菜单。
我正在工作的服务器没有实际版本,所以我使它更加灵活。这取决于作者是否愿意使用和尝试。

if (version_compare(PHP_VERSION, "5.4.0") >= 0) {
    $sess = session_status();
    if ($sess == PHP_SESSION_NONE) {
        session_start();
    }
} else {
    if (!$_SESSION) {
        session_start();
    }
}

Actually, it is now too late to explain it here anyway as its been solved.
This was a .inc file of one of my projects where you configure a menu for a restaurant by selecting a dish and remove/add or change the order.
The server I was working at did not had the actual version so I made it more flexible. It's up to the authors wish to use and try it out.

栖竹 2024-11-21 04:17:36

此代码片段适合您吗?

if (!count($_SESSION)>0) {
    session_start();
}

Is this code snippet work for you?

if (!count($_SESSION)>0) {
    session_start();
}
美人迟暮 2024-11-21 04:17:36

这是我用来确定会话是否已开始的方法。通过使用empty和isset,如下所示:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}

This is what I use to determine if a session has started. By using empty and isset as follows:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}
も让我眼熟你 2024-11-21 04:17:36

您应该重新组织代码,以便在每个页面执行时调用 session_start() 一次。

You should reorganize your code so that you call session_start() exactly once per page execution.

空名 2024-11-21 04:17:36

PHP_VERSION_ID 自 PHP 5.2.7 起可用,因此请先检查此项,如有必要,创建它。
session_status 从 PHP 5.4 开始可用,因此我们也必须检查这一点:

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();
    }
}

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();
    }
}
可是我不能没有你 2024-11-21 04:17:36

根据我的实践,在访问$_SESSION[]之前,每次使用该脚本都需要调用session_start。请参阅下面的链接获取手册。

http://php.net/manual/en/function.session-start。 php

对我来说,至少 session_start 作为一个名字是令人困惑的。 session_load 可以更清晰。

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.

池木 2024-11-21 04:17:36

我最终仔细检查了状态。 PHP 5.4+

if(session_status() !== PHP_SESSION_ACTIVE){session_start();};
if(session_status() !== PHP_SESSION_ACTIVE){die('session start failed');};

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');};
三五鸿雁 2024-11-21 04:17:36

您可以使用以下解决方案来检查 PHP 会话是否已启动:

if(session_id()== '')
{
   echo"Session isn't Start";
}
else
{
    echo"Session Started";
}

You can use the following solution to check if a PHP session has already started:

if(session_id()== '')
{
   echo"Session isn't Start";
}
else
{
    echo"Session Started";
}
守不住的情 2024-11-21 04:17:36

绝对最简单的方法:

(session_status()==2)?:session_start();

The absolute simplest way:

(session_status()==2)?:session_start();
四叶草在未来唯美盛开 2024-11-21 04:17:36
session_start();
if(!empty($_SESSION['user']))
{     
  //code;
}
else
{
    header("location:index.php");
}
session_start();
if(!empty($_SESSION['user']))
{     
  //code;
}
else
{
    header("location:index.php");
}
夕嗳→ 2024-11-21 04:17:36

tl;dr

推荐

if(session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if(session_status() === PHP_SESSION_NONE) {
    session_start();
}

不推荐

if(!isset($_SESSION)) {
    session_start();
}

# PHP < 5.4.0
if(session_id() === "") {
    session_start();
}

tl;dr

Recommended

if(session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

if(session_status() === PHP_SESSION_NONE) {
    session_start();
}

Not Recommended

if(!isset($_SESSION)) {
    session_start();
}

# PHP < 5.4.0
if(session_id() === "") {
    session_start();
}

入怼 2024-11-21 04:17:36

session_start(); 替换为:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        session_start();
        $a = TRUE;
    }
}

Replace session_start(); with:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        session_start();
        $a = TRUE;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文