PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let’s create a new page called «demo_session1.php». In this page, we start a new PHP session and set some session variables:
Example
// Set session variables
$_SESSION[«favcolor»] = «green»;
$_SESSION[«favanimal»] = «cat»;
echo «Session variables are set.»;
?>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called «demo_session2.php». From this page, we will access the session information we set on the first page («demo_session1.php»).
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
// Echo session variables that were set on previous page
echo «Favorite color is » . $_SESSION[«favcolor»] . «.
«;
echo «Favorite animal is » . $_SESSION[«favanimal»] . «.»;
?>
Another way to show all the session variable values for a user session is to run the following code:
Example
How does it work? How does it know it’s me?
Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
Modify a PHP Session Variable
To change a session variable, just overwrite it:
Example
// to change a session variable, just overwrite it
$_SESSION[«favcolor»] = «yellow»;
print_r($_SESSION);
?>
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy() :
Example
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
Introduction
Session support in PHP consists of a way to preserve certain data across subsequent accesses.
A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL.
The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() ) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.
If you turn on session.auto_start then the only way to put objects into your sessions is to load its class definition using auto_prepend_file in which you load the class definition else you will have to serialize() your object and unserialize() it afterwards.
$_SESSION (and all registered variables) are serialized internally by PHP using the serialization handler specified by the session.serialize_handler ini setting, after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.
Because session data is serialized, resource variables cannot be stored in the session.
Serialize handlers ( php and php_binary ) inherit register_globals limitations. Therefore, numeric index or string index contains special characters ( | and ! ) cannot be used. Using these will end up with errors at script shutdown. php_serialize does not have such limitations.
Note:
Please note when working with sessions that a record of a session is not created until a variable has been registered using the session_register() function or by adding a new key to the $_SESSION superglobal array. This holds true regardless of if a session has been started using the session_start() function.
User Contributed Notes
- Sessions
- Introduction
- Installing/Configuring
- Predefined Constants
- Examples
- Session Upload Progress
- Sessions and Security
- Session Functions
- SessionHandler
- SessionHandlerInterface
- SessionIdInterface
- SessionUpdateTimestampHandlerInterface
Session Functions
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: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 😉
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:
if( version_compare ( phpversion (), ‘4.3.0’ )>= 0 ) <
if(! ereg ( ‘^SESS3+$’ , $_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:
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.