Checking for PHP session without starting one?

后端 未结 3 660
感情败类
感情败类 2021-02-12 20:30

Is it possible to check for a session with out starting one?

The reason that I ask is, the app I am developing has an integrated admin interface. So when an admin is logg

相关标签:
3条回答
  • 2021-02-12 20:40

    You could check if the PHPSESSID cookie is set (the PHPSESSID name may have another name, depending on your server settings, check ini.session.name).

    But if all you fear is poluting your session dir, you can adjust session.gc_probability, session.gc_divisor and session.gc_maxlifetime to make them disappear faster.

    0 讨论(0)
  • 2021-02-12 20:54

    You'd be wanting session_id(), which returns empty string if no session is defined.

    The documentation indicates that empty string (which is not "nothing") is returned if no session is started.

    As the 2014 comments indicate (I wrote this answer in 2009), there is the possibility that a session could start if there is a cookie with a session id stored in it that could be picked up by session_start().

    As of PHP 5.4.0, we now have session_status() but this didn't exist in 2009.

    0 讨论(0)
  • 2021-02-12 20:54

    Here's a function that will do what you ask, which is checking whether a session exists before starting it:

    function sessionExists() {
        return (isset($_COOKIE[session_name()]));
    }
    

    If you want to test for it in the same request that you created it, you can do this instead:

    function sessionExists() {
        return (isset($_SESSION) || isset($_COOKIE[session_name()]));
    }
    
    0 讨论(0)
提交回复
热议问题