PHP 5.6.17 is available
    Edit Report a Bug

    Session Functions

    Table of Contents

    • session_abort — Discard session array changes and finish session
    • session_cache_expire — Return current cache expire
    • session_cache_limiter — Get and/or set the current cache limiter
    • session_commit — Alias of session_write_close
    • session_decode — Decodes session data from a session encoded string
    • session_destroy — Destroys all data registered to a session
    • session_encode — Encodes the current session data as a session encoded string
    • session_get_cookie_params — Get the session cookie parameters
    • session_id — Get and/or set the current session id
    • session_is_registered — Find out whether a global variable is registered in a session
    • session_module_name — Get and/or set the current session module
    • session_name — Get and/or set the current session name
    • session_regenerate_id — Update the current session id with a newly generated one
    • session_register_shutdown — Session shutdown function
    • session_register — Register one or more global variables with the current session
    • session_reset — Re-initialize session array with original values
    • session_save_path — Get and/or set the current session save path
    • session_set_cookie_params — Set the session cookie parameters
    • session_set_save_handler — Sets user-level session storage functions
    • session_start — Start new or resume existing session
    • session_status — Returns the current session status
    • session_unregister — Unregister a global variable from the current session
    • session_unset — Free all session variables
    • session_write_close — Write session data and end session
    spacer add a note

    User Contributed Notes 21 notes

    up
    down
    13
    hinom - iMasters
    7 years ago
    simple session test

    <?php
    /* [EDIT by danbrown AT php DOT net:
       The author of this note named this
       file tmp.php in his/her tests. If
       you save it as a different name,
       simply update the links at the
       bottom to reflect the change.] */

    session_start();

    $sessPath   = ini_get('session.save_path');
    $sessCookie = ini_get('session.cookie_path');
    $sessName   = ini_get('session.name');
    $sessVar    = 'foo';

    echo
    '<br>sessPath: ' . $sessPath;
    echo
    '<br>sessCookie: ' . $sessCookie;

    echo
    '<hr>';

    if( !isset(
    $_GET['p'] ) ){
       
    // instantiate new session var
       
    $_SESSION[$sessVar] = 'hello world';
    }else{
        if(
    $_GET['p'] == 1 ){

           
    // printing session value and global cookie PHPSESSID
           
    echo $sessVar . ': ';
            if( isset(
    $_SESSION[$sessVar] ) ){
                echo
    $_SESSION[$sessVar];
            }else{
                echo
    '[not exists]';
            }

            echo
    '<br>' . $sessName . ': ';

            if( isset(
    $_COOKIE[$sessName] ) ){
            echo
    $_COOKIE[$sessName];
            }else{
                if( isset(
    $_REQUEST[$sessName] ) ){
                echo
    $_REQUEST[$sessName];
                }else{
                    if( isset(
    $_SERVER['HTTP_COOKIE'] ) ){
                    echo
    $_SERVER['HTTP_COOKIE'];
                    }else{
                    echo
    'problem, check your PHP settings';
                    }
                }
            }

        }else{

           
    // destroy session by unset() function
           
    unset( $_SESSION[$sessVar] );

           
    // check if was destroyed
           
    if( !isset( $_SESSION[$sessVar] ) ){
                echo
    '<br>';
                echo
    $sessName . ' was "unseted"';
            }else{
                echo
    '<br>';
                echo
    $sessName . ' was not "unseted"';
            }

        }
    }
    ?>
    <hr>
    <a class=tmp.php?p=1>test 1 (printing session value)</a>
    <br>
    <a class=tmp.php?p=2>test 2 (kill session)</a>
    up
    down
    7
    Csar
    7 years ago
    There's a bug in Internet explorer in which sessions do not work if the name of the server is not a valid name. For example...if your server is called web_server (_ isn't a valid character), if you call a page which uses sessions like web_server/example.php your sessions won't work but sessions will work if you call the script like this
    [IP NUMBER]/example.php
    up
    down
    9
    Jeremy Speer
    5 years ago
    When working on a project, I found a need to switch live sessions between two different pieces of software. The documentation to do this is scattered all around different sites, especially in comments sections rather than examples. One difficulty I encountered was the session save handler for one of the applications was set, whereas the other was not. Now, I didn't code in the function session_set_save_handler(), instead I utilize that once I'm done with the function (manually), however this function could easily be extended to include that functionality. Basically, it is only overriding the system's default session save handler. To overcome this after you have used getSessionData(), just call session_write_close(), session_set_save_handler() with the appropriate values, then re-run session_name(), session_id() and session_start() with their appropriate values. If you don't know the session id, it's the string located in $_COOKIE[session_name], or $_REQUEST[session_name] if you are using trans_sid. [note: use caution with trusting data from $_REQUEST, if at all possible, use $_GET or $_POST instead depending on the page].

    <?php
    function getSessionData ($session_name = 'PHPSESSID', $session_save_handler = 'files') {
       
    $session_data = array();
       
    # did we get told what the old session id was? we can't continue it without that info
       
    if (array_key_exists($session_name, $_COOKIE)) {
           
    # save current session id
           
    $session_id = $_COOKIE[$session_name];
           
    $old_session_id = session_id();
           
           
    # write and close current session
           
    session_write_close();
           
           
    # grab old save handler, and switch to files
           
    $old_session_save_handler = ini_get('session.save_handler');
           
    ini_set('session.save_handler', $session_save_handler);
           
           
    # now we can switch the session over, capturing the old session name
           
    $old_session_name = session_name($session_name);
           
    session_id($session_id);
           
    session_start();
           
           
    # get the desired session data
           
    $session_data = $_SESSION;
           
           
    # close this session, switch back to the original handler, then restart the old session
           
    session_write_close();
           
    ini_set('session.save_handler', $old_session_save_handler);
           
    session_name($old_session_name);
           
    session_id($old_session_id);
           
    session_start();
        }
       
       
    # now return the data we just retrieved
       
    return $session_data;
    }
    ?>
    up
    down
    7
    Edemilson Lima <pulstar at gmail dot com>
    8 years ago
    Sessions and browser's tabs

    May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use 'Control+N' in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is "PHPSESSID" and all tabs will use it. There is a workaround and it rely only on changing the session's name.

    Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

    <?php
    if(version_compare(phpversion(),'4.3.0')>=0) {
        if(!
    ereg('^SESS[0-9]+$',$_REQUEST['SESSION_NAME'])) {
           
    $_REQUEST['SESSION_NAME']='SESS'.uniqid('');
        }
       
    output_add_rewrite_var('SESSION_NAME',$_REQUEST['SESSION_NAME']);
       
    session_name($_REQUEST['SESSION_NAME']);
    }
    ?>

    How it works:

    First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

    After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format "SESSIONxxxxx", where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

    uniqid('') will generate an unique id for a new session name. It don't need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don't know if this may post a treat to the web server. I don't think so.

    output_add_rewrite_var() will add automatically a pair of 'SESSION_NAME=SESSxxxxx' to each link and web form in your website. But to work properly, you will need to add it manually to any header('location') and Javascript code you have, like this:

    <?php
    header
    ('location: script.php?'.session_name().'='.session_id()
          .
    '&SESSION_NAME='.session_name());
    ?>
    <input type="image" src="/img/spacer.gif"> <?php
    echo session_name(); ?>=<?php echo session_id(); ?>&SESSION_NAME=<?php echo session_name(); ?>')" />

    The last function, session_name() will define the name of the actual session that the script will use.

    So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

    May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.
    up
    down
    5
    carl /a/ suchideas /o/ com
    8 years ago
    Another gotcha to add to this list is that using a relative session.save_path is a VERY BAD idea.

    You can just about pull it off, if you're very careful, but note two related points:

    1) The path is taken relative to the directory of the ORIGINALLY executed script, so unless all pages are run from the same directory, you'll have to set the directory separately in each individual subfolder

    2) If you call certain functions, such as session_regenerate_id(), PHP will try to take the session directory relative to the exectuable, or something like that, creating an error IN the executable. This provides slightly cryptic error messages, like this:

    0

    ... so don't even bother. Just use

    <?php ini_set("session.save_path",dirname(__FILE__)."/relative_path"); ?>

    (or equivalent) in a file which you know is always in the same place relative to the file.

    {PHP version 5.1.6}
    up
    down
    4
    Nigel Barlass
    8 years ago
    Lima's note on sessions and browser's tabs needs to be modified for my version of php as the call to uniqid('') will return an alphanumeric string.
    Hence the ereg statement should be:
    if(!ereg('^SESS[0-9a-z]+$',$_REQUEST['SESSION_NAME'])) {...
    up
    down
    2
    brfelipe08 at hotmail dot com
    6 years ago
    If you need to use sessions, and some accents required for some Latin-based languages, you should encode your files in ISO-8859-1.
    You will run into some problems if you try to use UTF-8 - with or without BOM -, and ANSI will not support accents.
    ISO-8859-1 will both support sessions and the accents.
    up
    down
    4
    Sam Yong - hellclanner at live dot com
    4 years ago
    The following has been tested true in PHP 5.3.5.

    Setting the session variables after the execution of the script i.e. in __destruct function, will not work.

    <?php

    class Example{

        function
    __destruct(){
           
    $_SESSION['test'] = true;
           
    session_write_close();
        }

    }

    ?>

    The above example will write nothing into the temporary session file, as I observed through a custom Session Save Handler.
    up
    down
    3
    pautzomat at web dot de
    12 years ago
    Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

    Of course, it says so in the documentation ('Passing the Session Id') and of course it makes perfectly sense to have that restriction, but here's what happened to me:
    I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

    $sHomeDirectory = 'my.server.com/one/of/my/projects'

    which was used to make sure that all automatically generated links had the right prefix (just like $cfg['PmaAbsoluteUri'] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn't a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there...)

    Skipping the 'http:' did the job.

    OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours... Just don't do it ;)
    up
    down
    3
    ted at tedmurph dot com
    5 years ago
    I was having problems with $_SESSION information not being written or being lost in a seemingly random way.  There was a Location: call being made deep in a Zend OAuth module, I am using an IIS server with PHP as a CGI, etc.

    The answer was simply that you need to have the domain be consistent for sessions to work consistently.  In my case, I was switching back and forth between www.EXAMPLE.com:888 and EXAMPLE.com:888.  The unusual port, the hidden Location: call, the handoff with OAuth, etc all served to confuse me, but the intermitent error was caused by this simple goof of keeping the domain consistent.
    up
    down
    2
    hinom06 [at] hotmail.co.jp
    5 years ago
    simple session test version 1.1

    <?php
    /* [EDIT by danbrown AT php DOT net:
       The author of this note named this
       file tmp.php in his/her tests. If
       you save it as a different name,
       simply update the links at the
       bottom to reflect the change.] */

    error_reporting( E_ALL
    gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.