HTTP is stateless. When you make a request, the request is sent
to the server and then the connection is terminated. When the response is
sent back, it is sent from the server to the client, and the connection is
again terminated. HTTP doesn't "remember" anything about previous requests
and responses: When you click a link on a page, the server doesn't remember
any of your previous requests or information about those requests.
This is unlike FTP (File Transfer Protocol, which you might have
used if you've ever uploaded/downloaded files using a client such as FileZilla
or CoreFTP), which is stateful.
FTP maintains the connection between the
client and the server and keeps track of state information about the connection.
HTTP is Stateless: the server doesn't remember you between
request/response cycles
The problem with a stateless protocol like HTTP is that you (as a developer)
often need to keep track of information about the user/client between
requests. For example, if your site is an online store, you need to keep
track of what items the user adds to their shopping cart as they navigate
from one page to another. Each time the user requests a new page, how does
the server "remember" what items the user already had in their cart?
One way to remember this kind of information is by using
cookies. Cookies are permanent but they can
only
store small amounts of text data. Additionally, many more savvy users
block cookies in their browser, as a privacy measure.
Another option many PHP developers prefer are sessions.
A session is a visit to a web site or application:
A session consists of
a user first loading your site/application, using and/or navigating around the
site/application, and then leaving the site/application.
A Session begins when a user accesses your application (any page,
generally). A Session ends when one of the following happens:
The session times out. A session times out after 30 minutes of
no activity, when there are no new requests made with a
specific session ID. The timeout value of 30 minutes can
be changed programmatically in your application.
Your code invalidates or destroys the session. For exmaple,
you might write code that destroys the session when a
user logs out.
The application or server shuts down or restarts.
When a Session is first created, a unique session ID
is generated for that session. The server stores the session ID along
with any other user data that was included in the request. The
server then sends the session ID back to the client in the response.
The client reads the session ID and stores it in
as a session cookie.
The server generates a unique session ID which is stored as a session cookie on the client machine
For the next request, and all subsequent requests, the session id
stored in the session cookie is sent along in the request object.
The server then reads the session ID in the request
and matches it to table of session data it has: the session data
with the same session ID belongs to that specific user during this
current session. Any new data can be added and associated with that
same session ID as neeeded.
Every request sends the session ID to the server so the server can look up the user's stored data
for
that session.
When the session expires or is terminated, the server deletes the stored
session data and releases the session ID and its resources. After this
occurs, the server doesn't remember the user or any of the stored data.
A developer can use a session variable to keep track of information as the user
navigates around the site, making different requests of the server.
For example, as the user shops around on your store's site, session variables
can be used to remember the items in a shopping cart. When the user navigates
to a new page, that page is requested using a new HTTP connection: the page's
code can use a special session ID to add, read, and edit
session variables stored on the server.
Sessions can somtimes be more advantageous than regular cookies:
Cookies are stored on the
user's computer, and many users not wishing to have their privacy violated
will configure their browser to refuse cookies but still allow
session cookies (although you will still have to add fallback code if
the user has chosen to block all cookies).
Additionally, cookies can only store text data
and to a maximum of 4096 bytes (that includes the cookie name, expiry date,
the cookie's value, etc). PHP Sessions don't have a maximum size, and
can contain text, numbers, arrays, or entire objects. However, the server
running the PHP scripts does have a configuration option called memory_limit,
which defines the maximum amount of memory allocated to a running script;
the default value is 128MB so clearly you wouldn't want to store
anything in a session that's close to 128MB in size.
In PHP, session information is stored in the global variable called
$_SESSION. $_SESSION is an associative
array where keys reference objects and values that you can add, edit,
and remove.
You programmatically start a session when the user visits one of your
pages, and the session ends when they leave your page, although you can
also programmatically remove data from the session and/or end the session.
Creating a Session
The first thing that you need to do if you want to store and
access session data is begin a session. This needs to be done on every page
of your site that is going to use the session data.
To start a session, we invoke the session_start()
function. The session_start() function will:
check to see if a session already exists:
If the session exists, the session is resumed and your
code can access any of the stored session data and add new
session data.
If the session doesn't exist, a new session is started: a
new session ID is generated by the server.
The session_start() function call must be
the first line of PHP code
in your page, and must even go above the HTML <!DOCTYPE> declaration.
Furthermore, the call to session_start() must be in every single page on
your site that uses the session variables.
Each session is assigned a unique Session ID. This identifies
each session as unique to a single user. session_start() checks to see
if a session with a specific session ID already exists or not. It generates
a new session ID if it needs to create a new sessions.
When a session is created and when data is added to the
session, the $_SESSION global associative array is automatically
populated with any session data stored on the server.
Adding and Reading Session Data
Once you have started or resumed a session, you can add data to it.
You simply make up a key and store your data as the value in the $_SESSION
variable. You can then read it back using the same key:
When you load this page, you'll see an error on your page similar to
the one below (obviously my path and line # might be different from yours):
Notice: Undefined index: example2 in
C:\Users\Wendi\Syst10199\projects\PHPExamples\index.php
on line 14
In an earlier lesson, we learned the isset()
function. We can use that to see if a session variable was set or not.
If a session variable was not set, it means it doesn't yet exist (perhaps
this is the user's first visit in the session).
In the code above, we've added a line of code (line 4) that checks to
see if $_SESSION["example2"] exists. If it does, we store that session
variable in the scalar variable $ex2. If the $_SESSION["example2"] session
variable doesn't exist, we store the string literal "no data set" in the
$ex2 variable. When you load the page, you'll see "no data set" echoed
onto the screen, because we've never created the example2 session variable.
Try adding some code at the bottom of the page that assigns a value
to the example2 session variable, then reload the page and see if that
value outputs onto the screen.
You can modify a session variable any time using an assignment
statement, e.g. $_SESSION["example1"] = "Bye";
Removing Session Variables and Ending Sessions
If you need to, you can remove session variables so that they no longer
exist. To remove a session variable, use the unset()
function. Pass the function the session variable you want to unset:
unset($_SESSION["example1"]);
To unset all of the session variables, use the session_unset() function:
session_unset();
If you want to end a session, use the session_destroy() function:
session_destroy();
This will destroy the session data for the current session.
However, this won't destroy the session cookie on the client machine
and won't necessarily destroy any global session variables.
If you want to destroy a session, a better way is to simply
delete all the session data manually:
$_SESSION = array();
This still won't delete the session cookie, but that's fine.
If you really want to destroy the cookie, check the
PHP Manual entry for session_destroy() for
some code that deletes the session cookie.
Note that a session will automatically destroy itself a certain
amount of time after the user closes the browser, navigates away
from your site, or remains inactive for a period of time. You don't necessarily
have to end the session unless you want to make sure it ends while the
user is still on your site. The amount of time it takes a session to
end automatically depends on the server settings: there
is an option called "session.gc_maxlifetime" that sets the
amount of time a session should stay alive.
Exercises
1. Add a file sessionTest1.php to your project and paste in
the following code:
5. Now that you've completed each exercise, add the following statement to
sessionTest4b.php in the body of the document after the if/else blocks:
var_dump($_SESSION);
6. Create a simple page that lets you
manage your session variables. Provide a list of
check boxes for each session variable that currently
exists so you can check off which ones you want to
delete, and some input fields where you can add a new
session variable.
Very simple UI for Session VariablesSelect variables to remove and/or add a new session variableAfter clicking SUBMIT on previous screen.
Tips:
Creating check boxes: use a foreach loop to iterate
through the $_SESSION array (foreach ($_SESSION as $key => $value)).
Inside the loop, create a labeled checkbox and use an
array as the name attribute value e.g. name='chk[]'
Using Delete All: use an if statement to check and
see if Delete All was checked - if it was, use one of the
PHP functions that removes all the session variables.
Otherwise, remove only the session variables that were
checked.