DEV Community

Cover image for PHP session
MONU DIXIT
MONU DIXIT

Posted on

PHP session

Index for this blog

  • Definition.

  • How to start session ?

  • How to store session variable ?

  • How to destroy session ?

  • How session works ?

Hello
Let's talk about the session in PHP.
So first of all what is a session -->
A session is a bundle or a bag of data that is related to the current web application (on PHP) that you are using.
(or)
A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.

How to start a session in PHP ?

<?php
     session_start();
?>
Enter fullscreen mode Exit fullscreen mode

When will you need to start the session ?

  • If you want that the user can only excess any page of your application after logged in. While loging in you can set myusername as user's name or email of user or any other thing blahhhh blahhh.....
<?php 
     if( isset($_SESSION["myusername"]) ){
         header("location:home.php");
     }
?>
Enter fullscreen mode Exit fullscreen mode
  • If you want to display logged in user's age in your application more than once - then you can fetch age from database only once and store it in session variable like -
<?php
     session_start();     
     $_SESSION['age'] = $age;
 ?>
Enter fullscreen mode Exit fullscreen mode

and use it wherever you want before destroying the session.

What is meant by destroying the session

  • Suppose you have done all the work on an application and now you want to log out from this application. You have to destroy the session in order to delete all your information stored in the session so that no one can use it for log in back to your account without your permission.
<?php
     session_destroy()
 ?>

Enter fullscreen mode Exit fullscreen mode

How session works ?

Image description

The session support allows you to store data between requests in the $_SESSION superglobal array. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated.

Top comments (0)