Session support in PHP consists of a way to preserve certain data across subsequent accesses.

Start a PHP Session

A session is started with the session_start() function. Session variables are set with the PHP global variable: $_SESSION.

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
$_SESSION["name"] = "codeshot";
echo date("Y m d H:i:s", $_SESSION["time"]);
echo "Session variables are set.";
?>

</body>
</html>
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

Get PHP Session Variable Values

Now, we will access the session information from above code.

Session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
echo "Favorite website is " . $_SESSION["name"] . ".<br>";
?>

</body>
</html>




Modify a PHP Session Variable

The modification of the variables can be done by overwriting the variable's value like this -

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
$_SESSION["name"] = "google";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session

session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.

<?php
session_start();
?>

<!DOCTYPE html>
<html>
<body>

<?php
session_unset(); 
session_destroy(); 
?>

</body>
</html>
session_unset() is used to unset all session variables and session_destroy() is used to destroy the session.