Script Code : PHP Sessions Starting, Setting and Closing

PHP Tutorial [Beginner’s Basic learning] – Sessions in PHP. Starting, Setting and Closing

Session(s) is a temporary storage of values/data to variables to be used for serving web user in a better and interactive way. The data stored in sessions can be either user provided or is being drawn from a stored database at server end.

Starting Php Session

Starting sessions in php is very easy and it is initiated by simple script code as shown here below

<?php
session_start(); // start up your PHP session!
?>

Displaying Values from PHP Session


<?php
session_start(); // start up your PHP session!
$_SESSION['user'] = "Guest"; // store session data
echo "Your Name is = ". $_SESSION['user']; //retrieve data
?>

above code will output the following line
Your name is = Guest.

Setting Session with isset

<?php
session_start();
if(isset($_SESSION['hits']))
$_SESSION['hits'] = $_SESSION['hits']+ 1;
else
$_SESSION['hits'] = 1;
// Now output page hits
echo "hits = ". $_SESSION['hits'];
?>

Closing Session in PHP coding

We have two options. Either we can remove session values with unset function like shown in PHP code given here below:

<?php
session_start();
if(isset($_SESSION['userID']))
unset($_SESSION['userID']);
?>

OR
We can destroy session with session_destroy function as shown here under :

<?php
session_start();
session_destroy();
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

*