What is Session in PHP?

While a user a make request to the server for a resource.A connection is made between client and server and connection is closed after response sent by Server.Each time a request is made to the server over HTTP protocol server treated it as new request.Server doesn’t know that the same user making the request.Sometimes we need a session for the users so that server can treat them as know users.

For resolving this issue session technique is used.Session is variable stored on the server.We can store following information in the session.

  • Cart information/products selected by users for an ecommerce site.
  • Logged in user’s information like user id,username etc
  • Hits count for a web page

and lots more.

When a session is created for a request server sends a cookie named PHPSESSID to browser and each time a request comes server checks for the PHPSESSID against stored sessions. For each request unique PHPSESSID  is created.Session can be fetched to any pages of the application.Default session alive for 30 mins.

Starting a PHP Session

A PHP session is started by session_start() function. It is recommended to placed session_start() at the beginning of the page.

Destroying a PHP Session

A PHP session can be destroyed by session_destroy() or unset() functions.

unset($_SESSION[‘session_created_by_yours’]);

Hits Counter for a Page


<?php
 session_start();
//checking for registered session
 if( isset( $_SESSION['counter'] ) ) { 
$_SESSION['counter'] += 1; } 
else {
 $_SESSION['counter'] = 1; 
} 
$message = "You have visited this page ". $_SESSION['counter'];
 ?>
<html>
   
   <head>
      <title>Page Counter Application</title>
   </head>
   
   <body>
      <?php echo ( $message ); ?>
   </body>
   
</html>

Leave a Reply