PHP Sessions

Written by admin on June 20th, 2007 in PHP Tutorials.

Well, today we are going to be learning about PHP Sessions. So lets get started.
A session is well, a session. It is a time period for a visit in PHP’s terms. It can keep all visitor information or any other information in it while navigating to different pages. But you cant just start using sessions in your page whenever you want. There is some header information we need to take care of.
So let’s get learning the session headers.

Sessions must be started before you can use them. So to start a new session we use the following code:

session_start(“session_name”);

The function speaks for itself. Start a session. the words in quotes is the name of the session. We need a name because if another website is open at the same time, we dont want the session conflicting with each other. So now we have that sorted we can get onto using sessions.

Everything to do with session is stored one one variable which is:

$_SESSION

You can store anything inside a session, whether it is numeric values or arrays. Let’s look at how to store something in our session.
To start with we need to make a variable.

$_SESSION[‘value’] = ;

Now we can place anything for the value of this session. the name of the variable is stored within the single quotes.
Every page that has the session headers defined will be able to display this session variable. By using things such as:

echo $_SESSION[‘value’];

You can use print_r to output everything that is stored in the session like so:

print_r($_SESSION);

Now it is unsecure to leave sessions open and sometimes you may need a fresh clean session. So to delete a session and all of its data we use the following php function:

session_unset(“session_name”);

If you want to completely delete the session you can use:

session_destroy(“session_name”);

This will completely erase everything to do with the session.

Hope this has helped with your udnerstanding of PHP sessions.

One Response to “PHP Sessions”

  1. PDStudios » Blog Archive » PHP Global Variables Says:

    […] more complex to use. This global variable uses sessions to function. Recommend you read up on the PHP Sessions tutorial before […]

Leave a Reply

You must be logged in to post a comment.



Site Navigation