Thursday, July 14, 2011

session in php

today i will show you how to register session's and delete session in php
but before starting i will give u a small introduction

format of session variable is $_SESSION["<variable name>"]
want to register a session for log-in or any other purpose like temporary settings.
session will be working till your page(s) are closed.

session variable are super-global variables means they can be used in any page.

for long purpose of storing data of user for next visit's like name,email cookies should be used.in my way i will show you how its done.

it's not long ago when i learned session but its practice can increase features of your website.

to initialise a session you must call a function session_start();
it return true on success and false on failure
failed to load this function will bring error and unpredictable output so be carefull to load this function first

to create a session variable [with name "dummy"]

<?php
 session_start();
 $_SESSION["dummy"]="dummy text goes here or any other data type";
?>

if you want to go a little advance you can use the below script
<?php
   session_start();
   if(isset($_SESSION["dummy"])) 
         echo "dummy variable already exists";
   else 
     {
       $_SESSION["dummy"]="dummy text goes here or any other data type";
       echo "dummy variable created";
     }
?>
if you run this script twice on server it will give this output
first run
dummy variable created
second run
dummy variable already exists

if you are planning to register user and provide them user name and password session variables come handy

for example
<?php
 session_start();
  if(isset($_SESSION["username"]))
       echo "welcome ".$_SESSION["username"];
  else
    {
      echo "checking username and password...\n";
      check_username_password(); /*dummy function to check
username and password*/
    }
function check_username_password()
{
   /------check username and password-------/
   /------check username and password-------/
   if(<authentication variable>)
    {
     /*authentication is successful*/
     $_SESSION["username"]=<received username>;
     echo "successfully logged in";
   }
   else
     {
      /*authentication failure*/
      echo "authentication failure."
     }
}
?>

now comes the last part if you register a session how to delete the session
php has inbuilt function to delete a session bool session_destroy( void )
bool session_destroy(void) will delete all session variable
it return true on sucess and false on failure
for example
log-out.php
<?php
  session_start();
  if(session_destroy()) 
      echo "session successfully destroyed";
  else 
      echo "error occurred while destroying session";
?>

that's all folk's
please comment and ask for a more advance tutorial if required.

Labels: , , , , , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home