How to Create,Access,and Destroy Session in PHP


Share:
Published By: Admin, Published On: Apr 17, 2021, Category: PHP

Hi Guys,

In this blog,I will explain you how to PHP session is used to store and pass information from one page to another ephemerally (until utilizer close the website).

PHP session technique is widely utilized in shopping websites where we require to store and pass cart information e.g. username, product code, product denomination, product price etc from one page to another.

PHP session engenders unique utilizer id for each browser to agnize the utilizer and avoid conflict between multiple browsers.

session_start()

The session_start() function is used to start the session. It starts a new or resumes existing session. It returns existing session if session is created already. If session is not available, it creates and returns new session.

Syntax:
bool session_start ( void )
Example
session_start();  
Create Session

PHP $_SESSION is an associative array that contains all session variables. It is utilized to set and get session variable values.

Example: Store information

Syntax:
$_SESSION["key"] = "value";  
Example: Get information
echo $_SESSION["key"];

PHP Session Full Example

Now,Let's see create a first session file:session_one.php.

<?php

    session_start(); 
    $_SESSION["user"] = "Bhavesh";  
    echo "Session information are set successfully.
"; ?> Visit next page
Output
Session information are set successfully.
Visit next page

Second file session_two.php

Example
<?php

    session_start();
    echo "User is: ".$_SESSION["user"];  

?>     
Output
User is: Bhavesh

PHP Session Counter Example

file:session_counter.php

Example
<?php

   session_start(); 
    
   if (!isset($_SESSION['counter'])) {  
      $_SESSION['counter'] = 1;  
   } else {  
      $_SESSION['counter']++;  
   }  
   echo ("Page Views: ".$_SESSION['counter']); 

?>

PHP Destroying Session

PHP session_destroy() function is used to destroy all session variables completely.

Third file destroy the session session_three.php

Example
<?php

    session_start();  
    session_destroy(); 

?>

It will help you..

Share: