A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the user's computer; it is stored on the server.
A session is started with the session_start() function. This must be the very first thing in your document, before any HTML tags.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<!-- Content -->
</body>
</html>
You can store data in the $_SESSION superglobal array. These variables will be available on all other pages in the same site.
<?php
session_start();
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
To access session data on a different page, you just need to call session_start() again and read from the $_SESSION array.
<?php
session_start();
echo "Favorite color is " . $_SESSION["favcolor"] . ".";
?>
To logout a user or clear all session data, you should use both session_unset() and session_destroy().
<?php
session_start();
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?>
isset($_SESSION['user_id']) at the top of protected pages to check if a user is logged in. If not, you can redirect them to the login page.
session_start() at the top of the file.session_unset() before session_destroy() for a clean logout.