478

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?

random
  • 9,324
  • 10
  • 63
  • 77
Logan
  • 9,611
  • 12
  • 38
  • 50
  • 2
    possible duplicate of [how do i check if session_start has been entered?](http://stackoverflow.com/questions/1788202/how-do-i-check-if-session-start-has-been-entered) – Richard Harrison Jul 25 '12 at 10:17
  • See also this answers of Stackoverflow:http://stackoverflow.com/questions/1545357/how-to-check-if-a-user-is-logged-in-in-php – contact-form.co_you_go Sep 04 '15 at 17:04

26 Answers26

804

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

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();
}
chris
  • 2,440
  • 17
  • 19
lovelyramos
  • 8,419
  • 1
  • 14
  • 17
  • 1
    I think there is a problem with the solution for PHP < 5.4. session_id is set the FIRST time session is started, but it is not deleted when session is closed. So for example, if there is, before of your snippet, a code like `session_start();session_write_close();`: then the if condition fails but we have no open session... – Nicolò Martini May 15 '14 at 11:26
  • @Nicolo Martini As I understand it: A session started with `session_start()` at the top of a script is CLOSED when the script exits, OR when `session_write_closed()` is called before the script exits. I.e. a session CLOSES when it's data is written to the session cookie and the session is unlocked for access by another script that also calls 'session_start'. CLOSING does NOT mean that the session is DESTROYED, therefore. You can close a session by exiting the current script or calling `session_write_close()`, and you can open it again by calling `session_start()`. My understanding, at least. – Stefan Dec 15 '16 at 12:00
  • 1
    Is this still a good way to start a session? Because in the link there is nothing related to this answer – csandreas1 Jun 01 '18 at 11:22
  • @csandreas1 you will see from the link the description of session_status and its expected return values. The answer to your question is yes! – lovelyramos Dec 05 '18 at 17:31
  • I've had this fail in some circumstances - I've used if(!isset($_SESSION)) with success – Scott May 29 '20 at 15:07
162

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.

Alex
  • 2,939
  • 3
  • 20
  • 44
  • 38
    It's not necessarily bad to not know if your session is started. If you're lazy-loading (only starting the session when it's first needed) then the test in your answer would be perfectly fine. – drewm Jun 06 '11 at 09:53
  • 1
    Also in some environments apache has session autostarting set up – LeonardChallis Sep 14 '12 at 18:32
  • An example for testing if session_id() returns empty string in an include file: – tgoneil Oct 05 '12 at 08:05
  • 3
    The comment about refactoring session management if you don't know if it's tarted or not is not really relevant. For example if coding advanced features into a WordPress theme you won't ever know if a plugin has already started using sessions without checking. The coding world isn't always that black and white :P – Jimbo Jonny Nov 27 '12 at 17:23
  • Mmm, good points indeed. I do concede that my comments are very subjective - I'll amend my answer to reflect this. – Alex Mar 08 '13 at 12:58
  • Since this isn't a strict `===` comparison, I feel like it's safe to just say `if(!session_id())` – Anther Apr 19 '13 at 15:21
  • per php documentation, if the session is already started, the next sesion_start calls are just ignored (> php 4.3.3) . So you can call session_start as many times as you want – Alex Angelico May 17 '13 at 15:40
  • what about using `empty()` ? – Sisir Aug 22 '13 at 10:14
72

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
BenMorel
  • 30,280
  • 40
  • 163
  • 285
  • 3
    A snippet of code which uses session_status when available and older methods when not would seem to be perfect here BTW, hint hint :) – Jimbo Jonny Nov 27 '12 at 17:30
  • 1
    Thank you for the update Benjamin. It's good to know that a new method can be used as of PHP 5.4. – Logan Nov 28 '12 at 00:19
  • 1
    This is a much better way of checking this, you don't always know if you have a session started especially when the user clears cookies when they are in the middle of browsing the site... I always code for 2 year old's, you never know what users are going to do ;-) As for myself I have a small Config.php file that is called on all my scripts to setup variables and other info so just adding this in that file always assures that the session is started if it is needed – Andy Braham Jun 11 '13 at 18:03
36

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

if (!isset($_SESSION)) session_start();
Dharman
  • 21,838
  • 18
  • 57
  • 107
miyuru
  • 991
  • 10
  • 19
  • 7
    @zloctb: I can't think of any situation in which I'd do `$_SESSION=array();`, so this answer seems okay. – halfer Oct 19 '13 at 07:57
  • 5
    @halfer See Ryan's answer. If `session_destroy()` has been called then `$_SESSION` could still be set. Also, in unit tests you might set `$_SESSION` directly. But I upvoted this, as for most practical situations this answer should be good enough (until PHP 5.3 is never seen any more...) – Darren Cook Mar 02 '14 at 07:43
22
if (version_compare(phpversion(), '5.4.0', '<')) {
     if(session_id() == '') {
        session_start();
     }
 }
 else
 {
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
 }
k.bon
  • 268
  • 2
  • 9
21

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.

y o
  • 1,024
  • 8
  • 14
12

For all php version

if ((function_exists('session_status') 
  && session_status() !== PHP_SESSION_ACTIVE) || !session_id()) {
  session_start();
}
supersuphot
  • 540
  • 4
  • 8
9

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

Elshan
  • 5,941
  • 4
  • 55
  • 92
7

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();
}
BenMorel
  • 30,280
  • 40
  • 163
  • 285
Wesley van Opdorp
  • 14,433
  • 4
  • 39
  • 58
5
if (session_id() === "") { session_start(); }

hope it helps !

Mahesh Cheliya
  • 1,136
  • 1
  • 15
  • 20
5

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();
    }
  }
}
Dustin Poissant
  • 2,710
  • 1
  • 17
  • 22
4

The only thing you need to do is:

<?php
if(!isset($_SESSION))
{
session_start();
}
?>
  • This is the one I've used troughout the years. Anyone advicing not to use this one? Ofcourse it's good to use a check if session is started sometimes - in some environments apache has session autostarting set up, lazy-loading (only starting the session when it's first needed) or simply that one sometimes need to just make a fast hack – K. Kilian Lindberg Apr 01 '14 at 09:49
  • IS THE SAME RESPONSE ABOVE (@miyuru) –  Apr 15 '16 at 16:55
2

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;
  }
Alex Khimich
  • 518
  • 4
  • 8
2

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

crabbly
  • 4,551
  • 1
  • 17
  • 42
1

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.

1

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

Thielicious
  • 3,054
  • 2
  • 22
  • 31
1

Is this code snippet work for you?

if (!count($_SESSION)>0) {
    session_start();
}
NiroshanJ
  • 517
  • 1
  • 4
  • 17
1

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();
}
Suit Boy Apps
  • 3,005
  • 8
  • 36
  • 54
Rotimi
  • 4,494
  • 4
  • 16
  • 27
0
session_start();
if(!empty($_SESSION['user']))
{     
  //code;
}
else
{
    header("location:index.php");
}
Tunaki
  • 116,530
  • 39
  • 281
  • 370
0

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

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.

Shree
  • 18,997
  • 28
  • 86
  • 133
Eduard Hasanaj
  • 453
  • 2
  • 7
0

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');};
Leo Tahk
  • 354
  • 1
  • 4
  • 13
0

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";
}
Grant Miller
  • 19,410
  • 15
  • 108
  • 135
Manjeet Kumar Nai
  • 1,004
  • 1
  • 9
  • 13
0

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

SamT
  • 9,464
  • 2
  • 29
  • 37
  • 4
    calling it exactly once per page execution might not be desired in some situations. – Timo Huovinen Apr 28 '12 at 13:37
  • If you're killing the session to recreate it, then sure, but that is a special case. In general, the application should have code that is ran at the very beginning once, which is where the session_start() goes. – SamT Apr 29 '12 at 22:51
  • 1
    for example, an application stores sessions on a file, and needs to load 2 concurrent slow requests of data, none of these requests need sessions, but one will block the other because session_start locks the session file. – Timo Huovinen Apr 30 '12 at 10:44
  • Exactly. @YuriKolovsky is right. The Alex's question is pertinent because these cases can happen, and they are not uncommon. – Paulo Coghi May 24 '12 at 11:56
  • 14
    -1, Most websites are CMS driven and have things such as themes and plugins, often written by different parties, never knowing if each other's code has started sessions or not. The implication that this is a code organization problem only is a false one. – Jimbo Jonny Nov 27 '12 at 17:27
-3

Replace session_start(); with:

if (!isset($a)) {
    a = False;
    if ($a == TRUE) {
        session_start();
        $a = TRUE;
    }
}
Nikolay Mihaylov
  • 3,788
  • 8
  • 25
  • 32
  • it contains code errors and would only work, if the same file would be included multiple times, but not if within a closure. – BananaAcid Sep 14 '17 at 20:39