downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

session_cache_expire  Sessions and security
[edit] Last updated: Fri, 15 Mar 2013

view this page in

Session Functions

Table of Contents

  • 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_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


session_cache_expire  Sessions and security
[edit] Last updated: Fri, 15 Mar 2013
 
 add a note User Contributed Notes Session Functions - [58 notes]
up
down
2
hinom06 [at] hotmail.co.jp
2 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 );
ini_set( 'display_errors', 1);
date_default_timezone_set('Asia/Tokyo');

//ini_set( 'session.save_path', '/tmp' ); // for debug purposes
  
session_start();

// check if session_id() exists.
/*
for example, if exists and session wont read, must send session.name as parameter in URL.

Some servers configurations may have problem to recognize PHPSESSID, even if transid value is 0 or 1. 
So, this test is usefull to identify any causes.

*/
if( session_id() == '' )
{
    echo
'session_id() empty';
}else{
    echo
session_id();
}
echo
'<hr>';

$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&<?php echo $sessName . '=' . session_id();?>>test 1 (printing session value)</a>
<br>
<a class=tmp.php?p=2&<?php echo $sessName . '=' . session_id();?>>test 2 (kill session)</a>
up
down
2
Nigel Barlass
5 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
Edemilson Lima <pulstar at gmail dot com>
5 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
3
Sam Yong - hellclanner at live dot com
1 year 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
0
edA-qa at disemia dot com
3 years ago
WARNING for Debian users.  Just to drive you completely crazy Debian does its own form of session management and will completely ignore all alterations to the values who do within your PHP script.

Debian sets up a <crontab /etc/cron.d/php5> which deletes all files, including those in subdirectories, which exceed the gc_maxlifetime specified in the <php.ini> file only.

That is, on Debian (and likely variants like Ubuntu) modifying the session expiration settings (like gc_maxlifetime) does *NOTHING*.  You *HAVE* to modify the global <php.ini>.  Not even a <.htaccess> file will help you.
up
down
0
jitchavan at gmail dot com
1 year ago
IE issue :-

when form target set to br source and after posting form content you are setting session variables,
In this scenario if parent page having image src blank then session values set in br action page will be LOST surprisingly in IE ONLY.Solution is quite simple don't keep Image src blank.
up
down
0
ted at tedmurph dot com
2 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
0
Trevor Brown
2 years ago
A confirmation of behaviour, just in case this saves anyone else some time...

There is (potentially) a special case when session.gc_probability = 0 and session.gc_divisor = 0.  Depending on how they wanted to work their maths underneath, the coders *might* have opted to interpret 0/0 as 1 (which is sometimes assumed in certain maths proofs), but thankfully it seems they haven't.  With both values set to 0, the session code will follow the spirit of the directives and invoke the garbage collector with zero probability.  At least this is true with php 5.2.5 (which, to be certain, I inspected the source of).

To be safe, however, setting both to zero is *probably* not a good idea because usually 0/0 is undefined, so it could presumably mean anything (some arguments exist that claim 0/0 is equal to every fraction).  Wouldn't you rather know for sure what your probability was set to?  In other words, don't set gc_divisor = 0
up
down
0
Jeremy Speer
3 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
0
brfelipe08 at hotmail dot com
3 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
0
edA-qa at disemia dot com
3 years ago
Sessions may be deleted before the time limit you set in gc_maxlifetime.

If you have multiple pages on the same server, each using the session (the same or distinct named sessions, it doesn't matter), the *minimum* gc_maxlifetime of any of those scripts ends up being the effective lifetime of the session files.

This can also apply to the lifetime coming from a CLI invocation of a PHP script on that machine which happens to use the session.

This can be bothersome since even though you think all your pages include the same file which sets up the script, even a single PHP page which doesn't can invoke the GC and have the scripts deleted.

Thus, if you need to set a long gc_maxlifetime you are best doing this through the INI file or in a .htaccess file for the entire directory.
up
down
0
LaurentT
4 years ago
For UNIX :

One might encounter some problems with sessions, having different sites on the same server : sessions would either merge if one is using more than one site at a time or crash if sites are owned by different system users. For instance :

www.example.com is stored in /home/site1/www
www.example.net is stored in /home/site2/www

Using both www.example.com and www.example.net would cause sessions to act weird.

If you're using PHP as an Apache module, you can easely use php_value in the http.conf to set a unique session.name depending on the site. If you're using suPHP though (PHP as CGI) you can't use php_value, though you can use suPHP_ConfigPath.

Here's an example :

<VirtualHost 10.10.10.10:8081>
    DocumentRoot /home/site1/www
    ServerName www.example.com
    suPHP_ConfigPath /home/site1/server_config
</VirtualHost>
<VirtualHost 10.10.10.10:8082>
    DocumentRoot /home/site2/www
    ServerName www.example.net
    suPHP_ConfigPath /home/site2/server_config
</VirtualHost>

Each server_config folder contain a php.ini file specific to the vHost. You then just have to change the values of each session.name to unique ones and you're done !
up
down
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.