Monday, 23 October 2017

Starting a PHP Session

Starting a PHP Session
A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page. Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session. The following example starts a session then registers a variable called counter that is incremented each time the page is visited during the session. Make use of isset() function to check if session variable is already set or not. Put this code in a test.php file and load this file many times to see the result
eg:-<?php
   session_start();
   if( isset( $_SESSION['counter'] ) ) 
   {
      $_SESSION['counter'] += 1;
   }
  else 
  {
      $_SESSION['counter'] = 1;
   }
   $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
?>
<html>
   <head>
      <title>Setting up a PHP session</title>
   </head>
   <body>
      <?php  echo ( $msg ); ?>
   </body>
</html>

It will produce the following result −
You have visited this page 1in this session.

Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not need any argument and a single call can destroy all the session variables. If you want to destroy a single session variable then you can use unset() function to unset a session variable.

Here is the example to unset a single variable −
<?php
   unset($_SESSION['counter']);
?>

Here is the call which will destroy all the session variables −
<?php
   session_destroy();
?>
Turning on Auto Session
You don't need to call start_session() function to start a session when a user visits your site if you can set session.auto_start variable to 1 in php.ini file.
https://www.youtube.com/channel/UCKLRUr6U5OFeu7FLOpQ-FSw/videos

0 comments

Post a Comment