This tutorial shows you how to work with
sessions in PHP. You will learn how to transfer information between
pages to create interactive environments for users to send information,
remain logged in, and so on.
PHP session tutorial
Step 1 - Session basics
PHP session tutorial
As
you may know HTTP is a stateless protocol which means that each server
request knows nothing about the others. What does it mean in our case?
Suppose
a login system where a visitor can log in and the logged in users have
more rights on the site. It means that the login page, let's say
login.php has information about the user. However if the user visits a
page eg.: myprofile.php then you lose all of the data you have on
login.php. So on each page load all old datav will be lost.
To
solve this problem the sessions were introduced in PHP. Using sessions
you can transfer data between various pages. If you are using sessions
then each of your visitors will got a unique id. This id will identify
various visitors and with the help of this id are the user data stored
on the server.
Session handling can be fine tune with PHP
parameters. Just run the following small code and you will get you
actual PHP settings:
If you scroll down in the output you will find a complete section with session settings like this:
session
| Session Support |
enabled |
| Registered save handlers |
files user |
| Registered serializer handlers |
php php_binary wddx |
| Directive |
Local Value |
Master Value |
| session.auto_start |
Off |
Off |
| session.bug_compat_42 |
Off |
Off |
Step 2 - Most important session parameters
In
this section I will explain the most important session parameters. If
one or more example from this tutorial doesn't work then you need to
check these session parameters.
- session.auto_start : specifies whether the session module starts a session automatically on request startup. Defaults to 0 (disabled).
- session.name
: specifies the name of the session which is used as cookie name. It
should only contain alphanumeric characters. Defaults to PHPSESSID.
- session.save_handler :
defines the name of the handler which is used for storing and
retrieving data associated with a session. Defaults to files.
- session.save_path
: defines the argument which is passed to the save handler. If you
choose the default files handler, this is the path where the files are
created. Defaults to /tmp.
- session.use_cookies : specifies whether the module will use cookies to store the session id on the client side. Defaults to 1 (enabled).
- session.use_only_cookies
: specifies whether the module will only use cookies to store the
session id on the client side. Enabling this setting prevents attacks
involved passing session ids in URLs.
- session.cookie_lifetime
: specifies the lifetime of the cookie in seconds which is sent to the
browser. The value 0 means "until the browser is closed." Defaults to 0.
- session.cookie_path : specifies path to set in session_cookie. Defaults to /.
- session.use_trans_sid : whether transparent sid support is enabled or not. Defaults to 0 (disabled).
The only you maybe need to change is the session.save_path. Choose a valid and writeable directory.
Step 3 - Starting a session
PHP session tutorial
After the introduction it's time to implement your first session based web site.
First of all you need to start the session with the session_start()
function. Note that this function should be called before any output
is generated! This function initialise the $_SESSION superglobal array
where you can store your data. So for example let's store user name in
the session. You can do it as follows:
Code: session.php
-
-
$_SESSION['username'] = 'John';
-
Now if you create a new file where you want to display the username you
need to start the session again. In this case PHP checks whether
session data are sored with the actual id or not. If it can find it
then initialise the $_SESSION array with that values else the array
will be empty. So a code which displays the username looks like this:
Code: session2.php
-
-
echo "User : ". $_SESSION['username'];
-
That's it. If it doesn't work then check your session settings as mentioned in step 2.
Step 4 - Check sessions
PHP session tutorial
In
the previous example I used 2 different files to demonstarte basic
session behaviour. However by checking session status we can create a
much better code. To check whether a session variable exists or not you
can use the isset() function.
So
in the next code we will first check if the username is set or not. If
it is not set yet then we will set it else we will display it. As
result if call the code twice you will get different output. The code
is the following:
Code:
-
session_start();
-
if (isset($_SESSION['username'])){
-
echo "User : ". $_SESSION['username'];
-
} else {
-
-
$_SESSION['username'] = 'John';
-
}
-
However if you have executed the first example as well then you will
never get the message "Set the username" as you have done it in your
very first call. If you wait until the session is expired and execute
the code again you will get the set message.
In the next step you will learn how to clean session data.
Step 5 - Clean and destroy session
PHP session tutorial
Sometimes
it is important to remove a session variable or destroy the complete
session. Such mechanism is used for example during a user logs out from
a site.
To remove a variable from a session is quite easy. You just have to call the unset() function to do this. Now you can extend our example code to unset the username as follows:
Code:
-
-
if (isset($_SESSION['username'])){
-
echo "User : ". $_SESSION['username'];
-
unset ($_SESSION['username']);
-
} else {
-
-
$_SESSION['username'] = 'John';
-
}
The result of this code is similar to a login/logout system. If the
user is logged in then we display the name than log him off. In the
next execution we log him in again.
You can use the session_destroy() function if you want to remove all session data, but be careful with it.
Code:
-
-
if (isset($_SESSION['username'])){
-
echo "User : ". $_SESSION['username'];
-
-
} else {
-
-
$_SESSION['username'] = 'John';
-
}
-
|