- PHP Sessions
- What is a PHP Session?
- Start a PHP Session
- Example
- Get PHP Session Variable Values
- Example
- Example
- Modify a PHP Session Variable
- Example
- Destroy a PHP Session
- Example
- Reading, Writing, and Removing Sessions
- Starting a Session
- Using Session Variables
- Closing Sessions
- DESCRIPTION
- OPTIONS
- EXAMPLE
- NOTES
- TODO
- AUTHOR
- SEE ALSO
- Module Install Instructions
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();
?>
Reading, Writing, and Removing Sessions
In this tutorial, we discuss how to use PHP sessions, showing how sessions are started and ended and how session variables are used.
When a user first enters the session-based application by making a request to a page that starts a session, PHP generates a session ID and creates a file that stores the session-related variables. PHP sets a cookie to hold the session ID in the response the script generates. The browser then records the cookie and includes it in subsequent requests.
The default configuration of PHP session management uses disk-based files to store session variables. Using files as the session store is adequate for most applications in which the numbers of concurrent sessions are limited. (We’ll discuss later a more scalable solution that uses a database).
Starting a Session
PHP provides a session_start( ) function that creates a new session and subsequently identifies and establishes an existing one. Either way, a call to the session_start( ) function initializes a session.
Note:
You don’t need to use session_start() function if you’ve activated the sessions globally with the php.ini directive:
session.auto_start = 1 .
The first time a PHP script calls session_start( ) , a session identifier is generated, and, by default, a Set-Cookie header field is included in the response. The response sets up a session cookie in the browser with the name PHPSESSID and the value of the session identifier. The PHP session management automatically includes the cookie without the need to call to the setcookie( ) or header( ) functions.
The session identifier (ID) is a random string of 32 hexadecimal digits, such as fcc17f071bca9bf7f85ca281094390b4 . As with other cookies, the value of the session ID is made available to PHP scripts in the $_COOKIE[‘PHPSESSID’] associative array.
When a new session is started, PHP creates a session file. With the default configuration, session files are written in the /tmp directory using the session identifier, prefixed with sess_ , for the filename. The filename associated with our example session ID is /tmp/sess_fcc17f071bca9bf7f85ca281094390b4 .
If a call is made to session_start( ) , and the request contains the PHPSESSID cookie, PHP attempts to find the session file and initialize the associated session variables as discussed in the next section. However, if the identified session file can’t be found, session_start( ) creates an empty session file.
Using Session Variables
All session data is accessible from a PHP script via the $_SESSION array. Because the data itself is stored on the server side, you can write session data and read it in the next PHP statement, without the requirement of a round-trip to the server as it was with cookies. Just remember to call session_start() first and then access $_SESSION .
Example: Registering Session Variables
Now print it on the second page:
Unsetting Session Variables:
Variables can be removed from a session with unset() function:
Use session_unset() function to unset all session variables:
Admin [email] => admin@brainbell.com ) session_unset(); print_r( $_SESSION ); // Array ( )
PHP stores session variables in the session file by serializing the values. The serialized representation of a variable includes the name, the type, and the value as a stream of characters suitable for writing to a file. Here’s an example of a session file:
user|s:5:"Admin";email|s:19:"admin@brainbell.com";
A PHP developer need not worry about how serialization occurs. PHP session management takes care of reading and writing session variables automatically.
Closing Sessions
In some instances, for example, when a user logs out, all session data should be removed, and the session must be closed. Of course, it would be possible to loop through $_SESSION with foreach and then set each value to an empty string or null, but there is a quicker way. Call session_destroy() . A session must be initialized before the session_destroy( ) call can be made.
A call to session_destroy( ) removes the session file from the system but doesn’t remove the PHPSESSID cookie from the browser.
Cookies and Sessions:
DESCRIPTION
PHP::Session provides a way to read / write PHP4 session files, with which you can make your Perl application session shared with PHP4.
If you like Apache::Session interface for session management, there is a glue for Apache::Session of this module, Apache::Session::PHP.
OPTIONS
Constructor new takes some options as hashref.
path to directory where session files are stored. default: /tmp .
type of serialization handler. Currently only PHP default serialization is supported.
whether to create session file, if it’s not existent yet. default: 0
whether to save modification to session file automatically. default: 0
my $session = PHP::Session->new($sid, < auto_save =>1 >); $session->set(foo => 'bar'); # Oops, you forgot save() method!
If you set auto_save to true value and when you forget to call save method after parameter modification, this module would save session file automatically when session object goes out of scope.
If you set it to 0 (default) and turn warnings on, this module would give you a warning like:
PHP::Session: some keys are changed but not modified.
EXAMPLE
use strict; use PHP::Session; use CGI::Lite; my $session_name = 'PHPSESSID'; # change this if needed print "Content-type: text/plain\n\n"; my $cgi = new CGI::Lite; my $cookies = $cgi->parse_cookies; if ($cookies->) < my $session = PHP::Session->new($cookies->); # now, try to print uid variable from PHP session print "uid:",Dumper($session->get('uid')); > else
NOTES
- Array in PHP is hash in Perl.
- Objects in PHP are restored as objects blessed into PHP::Session::Object (Null class) and original class name is stored in _class key.
- Locking when save()ing data is acquired via exclusive flock , same as PHP implementation.
- Not tested so much, thus there may be some bugs in (des|s)erialization code. If you find any, tell me via email.
TODO
AUTHOR
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
SEE ALSO
Module Install Instructions
To install PHP::Session, copy and paste the appropriate command in to your terminal.
perl -MCPAN -e shell install PHP::Session
For more information on module installation, please visit the detailed CPAN module installation guide.