Working with Sessions in PHP

Working with Sessions in PHP

Session Basics

  • cookies are not secure because they stored on the client, it’s possible for any user to open the cookie file and read or modify the information stored within it, sometimes to malicious ends.
  • Sessions work as cookies, except that the information maintains and store the state on the server.
  • A session is a method for storing information about one single user as a variable which used in multiple pages.
  • It creates a file in a temporary directory on the server for storing values of registered session variables.
  • This data will be available to all pages on the site during that visit.
  • By default, session variables used until the user closes the browser.
  • The location of the temporary file is setting in the php.ini file called session. save_path.
  • Every client is identified by a unique number—called session identifier—and this unique number is used to link each client with its information on the server and each browser to recognize the user and avoid conflict between multiple browsers.
  • The session IDs are randomly generated by the PHP engine.
  • Every time the client visits the Web site or application, the site reads the client’s session identifier and restores state information from a data repository on the server.
  • State information is stored in an SQL database or text file on the server; as a result, users cannot access or modify it, making the entire system that much more secure.
  • The session identifier itself may be stored on the client in a cookie, or it may be passed from page to page in the URL. Under PHP, this cookie is named PHPSESSID.
  • PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g., username, product code, product name, product price, etc from one page to another.
  • The PHP functions to create sessions, register and use session variables, and destroy sessions.

Creating Sessions (Start a PHP Session)

  • A PHP session is started by 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 call session_start() at the beginning of the page.
  • Session variables are stored in associative array called $_SESSION [ ]
  • These variables can be accessed during the lifetime of a session.

Example:-  

Register a session variable as a counter that is incremented each time the page is visited.

<?php

   session_start();

   // isset() function to check if session variable is already set or not.

   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>

Result −

You have visited this page 1in this session.


Now, Set session variables in "ss1.php".

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Output:-

Session variables are set.

PHP Session Variable Values

All session variable values are stored in the global $_SESSION variable.

We create another page called "ss2.php". From this page, access the session information set on the first page ("ss1.php").


Notice:- Session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).


Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Output:-

Example Favorite color is green.
The favorite animal is a cat.


Show all the session variable values by the array for a user session:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Ouput:-

Array ( [favcolor] => green [favanimal] => cat )


Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Output:-

Array ( [favcolor] => yellow [favanimal] => cat )


Turning on Auto Session

No 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.


Sessions without cookies

  • when a user does not allow to store cookies on their machine. 
  • Then we use another method to send session ID to the browser.
  • Alternatively, use the constant SID which is defined if the session started. 
  • If the client did not send an appropriate session cookie, it has the form session_name=session_id. Otherwise, it expands to an empty string. 
  • Thus, you can embed it unconditionally into URLs.

Example:- register a variable, and link correctly to another page using SID.

<?php
   session_start();
   if (isset($_SESSION['counter'])) {
      $_SESSION['counter'] = 1;
   }else {
      $_SESSION['counter']++;
   }
      $msg = "You have visited this page ".  $_SESSION['counter'];
   $msg .= "in this session.";
   echo ( $msg );
?>
<p>   To continue  click following link <br />
      <a  href = "nextpage.php?<?php echo htmlspecialchars(SID); ?>">
</p>

Result

You have visited page 1in this session.

To continue click the following link


Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();

echo "session destroyed ";
?>

</body>
</html>

Output:-

Session destroyed

 ================================================


Post a Comment

0 Comments