Lokang 

PHP and MySQL

Session

Sessions in PHP are used to store user information across different pages. Unlike cookies, session data is stored on the server. Here’s a basic example of how to start a session, store data in a session, retrieve session data, and destroy a session.

Starting a Session and Storing Data

Create a file called start_session.php:

<?php
// Start the session
session_start();
// Store data in session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john.doe@example.com";
echo "Session variables are set.";
?>

Retrieving Session Data

Create a file called retrieve_session.php:

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Retrieve Session</title>
</head>
<body>
   <?php
   // Retrieve session data
   if(isset($_SESSION["username"]) && isset($_SESSION["email"])) {
       echo "Username: " . $_SESSION["username"] . "<br>";
       echo "Email: " . $_SESSION["email"];
   } else {
       echo "No session data found.";
   }
   ?>
</body>
</html>

Destroying a Session

Create a file called destroy_session.php:

<?php
// Start the session
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
echo "Session is destroyed.";
?>

Explanation

Starting a Session and Storing Data (start_session.php):

  • session_start(): Starts a new session or resumes an existing session.
  • $_SESSION["key"] = value: Stores data in session variables.

Retrieving Session Data (retrieve_session.php):

  • session_start(): Resumes the session started in start_session.php.
  • $_SESSION["key"]: Retrieves the value stored in a session variable.

Destroying a Session (destroy_session.php):

  • session_start(): Resumes the session.
  • $_SESSION = array(): Clears all session variables.
  • session_destroy(): Destroys the session.

Usage

Start a session:

  • Access start_session.php in your browser. This will set session variables.

Retrieve session data:

  • Access retrieve_session.php in your browser. This will display the session data set in start_session.php.

Destroy the session:

  • Access destroy_session.php in your browser. This will destroy the session and clear all session data.

By using these scripts, you can manage sessions effectively in PHP.