How To Start A PHP Session ?

Session is a special technique to store information of a user across the multiple pages. To begin with a new session, simply we use the PHP session_start() function. It is must to start a session in the top of every page.

Session variables are set with the PHP global variable $_SESSION.


Below is the simple example to start a new session.

<?php
// Start the sessionsession_start();


?>
<!DOCTYPE html>
<html>
  <body>
      <b> my website </b>
  </body>
</html>

Creation & Accessing Session Data :-

You can create session using $_SESSION[] php function. You can create a session variable as below example.
<?php
// Start the sessionsession_start();
//Storing session Data $_SESSION['email'] = 'phpmypassion@gmail.com'; $_SESSION['name'] = 'phpmypassion'; ?>
You can access a session data using below example.
<?php
// Start the sessionsession_start();
//Accessing session Data echo 'Email id is='.$_SESSION['email'].' and name is ='.$_SESSION['name']; ?>

Destroying a Session :-

You can destroy a session using unset() or session_destroy() function. Below are the example to destroy a session variable.
Unset() Example :-

<?php
// Start the session
session_start();

//Removing session Data
if(isset($_SESSION["email"])){
      unset($_SESSION['email']);
}  
?>
Session_destroy() Example :-
<?php
// Start the session
session_start();



//Accessing session Data
session_destroy();
?>

Related posts