Session is used to store (hold) and share (use) information or data between webpages of a website.

Session is one of the method of server side state management which allows to store (hold) and share (use) information or data between webpages of a website. Session data is stored in server, and it is more secure than client side state management techniques like cookies or query string.

How Session works

  1. Session is an associative array which stores data in key and value pair.
  2. When Session is created, PHP generates Random Unique 32 digit Hexadecimal code identifier.
  3. PHP creates a cookie name PHPSESSID, and send to client(user computer) which stores it to identify session on server.
  4. A file with same Unique 32 digit Hexadecimal code identifier is created at the server.

Create session in PHP

To use or Create session in PHP, it needs to be started first. To start a session use

session_start()
  1. It starts session and assigns unique ID for Session to store and retrieve data.
  2. This method should be the first line in PHP script.
  3. Must be in lowercase.
  4. Create as many session you need.

Syntax

session_start();

Example

<?php
  session_start();
?>
<html>
<head>
</head>
<body>
</body>
</html>

Set data to Session variable

<?php
 session_start();

 $_SESSION["Username"] = "PHP";

?>
$_SESSION[]It accepts a string parameter, which is session variable or key.
$_SESSION[“Username”]Here username is key, you can use any name in session key
$_SESSION[“Username”] = “PHP”;In session, PHP is value of session key username.

Get data from session variable

<?php
session_start();

echo $_SESSION["Username"];

?>

To get data from session, simply use $_SESSION[“Your_key”] and use it as needed.

Change to Session variable data

<?php
session_start();

$_SESSION["SayHello"] = "Hello From PHP session";
echo $_SESSION["Username"];

?>

Remove Session

session_unset() is a PHP method which removes all session variables at once.

<?php
session_start();

session_unset();

?>

Destroy session

session_destroy() is use to destroy all session.
<?php
session_start();

session_unset();
session_destroy();
?>