PHP sessions are a way to store information (variables) to be used across multiple pages.
Unlike cookies, which are stored on the client-side (in the browser), session data is stored on the server.
This allows for better security, as sensitive information isn't exposed to the client-side (browser).
Start a PHP Session
To use sessions in PHP, you need to call session_start() at the beginning of the script. This function must be called before any output (HTML, text, etc.) is sent to the browser.
Now, let's create a new page called "demo_session.php". In this page, we start a new PHP session and set some session variables:
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["username"] = "JohnDoe";
$_SESSION["email"] = "john.doe@example.com";
echo"Session variables are set.";
?>
</body>
</html>
Get PHP Session Variable Values
Next, we create another page called "get_session.php". From this page, we will access the session information we set on the first page ("demo_session.php").
Notice that 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()).
Also notice that all session variable values are stored in the global $_SESSION variable:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
We use cookies and similar technologies to enhance your browsing experience, serve personalized content and advertisements, and analyze our traffic.
By clicking "Accept All", you consent to our use of cookies and the processing of your personal data for these purposes.
You can manage your preferences or learn more in our
Privacy Policy and
Cookie Policy.