Sessions in PHP

Status
Not open for further replies.

Baljeet

Member
Jan 31, 2011
76
0
Sessions is a good way for storing temporary data between your pages. A session is usually closed pretty fast after that the user have left the site so as I said, it's good for temporary storage, an example is the user's name or items the user have put in his/her shopping cart.




Starting a Session

To use a session you first have to start it, the session must be started before anything is sent to the page so you can't have any html tags before you starts the session. To start a new session you do like this:

PHP:
<?php
session_start();
?>


But since there's no point in starting a session that is already started we can first check if there's any sessions:

PHP:
<?php 
if(!isset($_SESSION))
{
session_start();
}
?>






Session variables

The data stored in a session is stored in different session variables, to read or write from/to a session variable you use $_SESSION['']; together with the name of the session.


An example on writing:

PHP:
<?php 
$_SESSION['username'] = "Me"; 
?>


An example on reading:

PHP:
<?php 
echo "Hello " . $_SESSION['username'] . "!"; 
?>


If you want to check if a session variable has been set you only use isset on the session variable, like so:

PHP:
<?php 
if (isset($_SESSION['username'])) {
echo "The session variable called username as the value " . $_SESSION['username'];
}else{
echo "The session variable called username haven't been set yet.";
}
 
?>





Remove session variables

You can also delete a session variable and all its info by using unset. Make sure this session variable exists first since there no point trying to remove anything that doesn't exists. Remember that this info will be lost forever. Here comes an example on how you can use unset after you've checked if the session variable exists:


PHP:
<?php

if (isset($_SESSION['username'])) {
echo "Bye " . $_SESSION['username'];
unset($_SESSION['username']);
}

?>



Destroying your session

If you're completely finished with the whole session you can remove it. This will make all your information disappear so only use it when you don't have any necessary information in it left, also remember to make sure that's the case. Same here, there's no idea to try to delete a session that doesn't exist so before destroying the session (by using session_destroy();) it could be a good idea to check if it exists. Here's how you do it:



PHP:
<?php 
if(isset($_SESSION))
{
session_destroy();
}
?>



That was everything for this tutorial. If you wonder anything just ask :)

All Credits goes to one who really made this...
 
Status
Not open for further replies.

Users who are viewing this thread

Top