logo
logo

Get in touch

Awesome Image Awesome Image

Development May 19, 2014

How to use sessions [ PHP Tutorial ]

Writen by Taeyaar Support

comments 0

Session is defined as $_SESSION[‘varname’] in PHP. A session makes the web pages interaction in easy manner. Basically, session is used to store variables that can be used by multiple pages on same server. It’s totally different from cookie system whereas cookie is stored on client side and so we can’t share confidential information over cookies like login/register password or credit card details. You don’t have to describe session variables at each page, but you can retrieve the on going session variables at the top of your php script.

session_start();
This command is used to start the session or to retrieve the session variables are being stored by server. To describe it more deeply, I’m going to use an example:
Let’s create a file name first.php


first.php


 <?php
session_start(); // Starting the sessions / Retrieving the on going session variables
$_SESSION[‘author’] = “Sahil Sharma”;
$_SESSION[‘website’] = “www.web-developer-sahil.blogspot.com”;
echo “Session Variables created!”;
?>


 In above first.php file, we’ve created two session variables $_SESSION[‘author’] and $_SESSION[‘website’]. And we can retrieve these two variables from any webpage [ but on same server ]. Lets create another one to retrieve these variables, I’m going to name it second.php


second.php


 <?php
session_start(); // We’ve retrieved the both session variables now.
echo $_SESSION[‘author’] . “‘ve sucessfully created the post for “.$_SESSION[‘website’];
?>


But keep in mind, you’ve to visit first.php first in order to get correct result in second.php because first variables are defined in first.php not in second.php.

session_destroy();
This command is used to destroy all the session variables for user on server. It’s basically used on logout pages. Hope, you’ve understood the basic usage of sessions in php. It was quiet simple and I know you can make much more things with it.

Tags : ,