Last 5.3 release ever available: PHP 5.3.29 - 5.3 now EOL

Basic usage

Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data. The absence of an ID or session cookie lets PHP know to create a new session, and generate a new session ID.

Sessions follow a simple workflow. When a session is started, PHP will either retrieve an existing session using the ID passed (usually from a session cookie) or if no session is passed it will create a new session. PHP will populate the $_SESSION superglobal with any session data after the session has started. When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.

By default, PHP uses the internal files save handler which is set by session.save_handler. This saves session data on the server at the location specified by the session.save_path configuration directive.

Sessions can be started manually using the session_start() function. If the session.auto_start directive is set to 1, a session will automatically start on request startup.

Sessions normally shutdown automatically when PHP is finished executing a script, but can be manually shutdown using the session_write_close() function.

Example #1 Registering a variable with $_SESSION.

<?php
session_start
();
if (!isset(
$_SESSION['count'])) {
  
$_SESSION['count'] = 0;
} else {
  
$_SESSION['count']++;
}
?>

Example #2 Unregistering a variable with $_SESSION.

<?php
session_start
();
unset(
$_SESSION['count']);
?>

Caution

Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.

Warning

You can't use references in session variables as there is no feasible way to restore a reference to another variable.

Warning

register_globals will overwrite variables in the global scope whose names are shared with session variables. Please see Using Register Globals for details.

Note:

File based sessions (the default in PHP) lock the session file once a session is opened via session_start() or implicitly via session.auto_start. Once locked, no other script can access the same session file until it has been closed by the first script terminating or calling session_write_close().

This is most likely to be an issue on Web sites that use AJAX heavily and have multiple concurrent requests. The easiest way to deal with it is to call session_write_close() as soon as any required changes to the session have been made, preferably early in the script. Alternatively, a different session backend that does support concurrency could be used.

add a note add a note

User Contributed Notes 4 notes

up
14
AlexFBP
1 year ago
Regardless, if you need to set the header 'Location:' before closing the session; explicitly close the php script with "exit()" or "die()" functions. Remember that when a php script ends, the session automatically are going to be closed.
up
-3
guy at syntheticwebapps dot com
10 months ago
Despite the warning about not being able to use references inside the session space, I've done it in the past and apparently completely successfully. That is, I can do something like this:

<?php
session_start
();
if (!
$_SESSION['favorite']) {
   
$_SESSION['cow'] = "Elsie";
   
$_SESSION['favorite'] =& $_SESSION['cow'];
    echo
"We set cow = '$_SESSION[cow]' and favorite =& cow ($_SESSION[favorite]).<br/>Reload the page to see if both change when one changes later.<br/>";
} else {
    echo
"Having re-entered the session after initial settings were made: cow = $_SESSION[cow] and favorite = $_SESSION[favorite].<br/>";
   
$_SESSION['cow'] = "Bessie";
    echo
"We reassigned cow = $_SESSION[cow] and our restored reference variable favorite = $_SESSION[favorite]<br/>Note the presence of the &s in the var_dump below.<pre>";
   
var_dump($_SESSION);
    echo
"</pre><br/>If you reload, the test will begin again.";
    unset(
$_SESSION['cow'], $_SESSION['favorite']);
   
session_destroy();
}
?>
yields the following after the second request:

Having re-entered the session after initial settings were made: cow = Elsie and favorite = Elsie.
We reassigned cow = Bessie and our restored reference variable favorite = Bessie
Note the presence of the &s in the var_dump below.
array(2) {
  ["cow"]=>
  &string(6) "Bessie"
  ["favorite"]=>
  &string(6) "Bessie"
}
If you reload, the test will begin again.

I've found this ability very useful and storage efficient in the session data.
up
-3
jpleveille at webgraphe dot com
1 year ago
As mentioned in the documentation, using session_write_close() shuts down the session. It is particularly useful if you want to use header('Location: SOMEURL'); to a URL within the same scope of the current script, that will load the session. Why?

When you use this header directive, the browser is requested to redirect the user to the given URL. If that URL is in the scope of the script where header() is called (let's say, same URL), the requested URL "COULD" load the session BEFORE it has actually been shut down in the previous script, and you might end up with the session from the previous request, reverting all modifications to session in the the last script.

<?php
session_start
();

if (!isset(
$_SESSION['hello']))
{
 
$_SESSION['hello'] = 'world';

 
session_write_close();
 
// session is now closed, it's safe to redirect
  // if not closed, $_SESSION['hello'] may not be set properly
  // when loading the page again
  // (in this very case, calls to this script could loop for a while)
 
header('Location: ' . $_SERVER['PHP_SELF']);
}
?>
up
-10
eddie at onefoldmedia dot com
7 months ago
If a session is not saving and you have verified that session_start() is being called, then double check capitalization. $_session can store variables but will not be treated like a session or cause an error.
To Top