Intermediate PHP: Sessions & Cookies
Go beyond the basics and master stateful web interactions in PHP using sessions and cookies — key tools for building dynamic, user-aware applications.
5. Understanding Sessions
Sessions are server-side containers for user data. Start them with session_start() before any output.
<?php
session_start();
$_SESSION['username'] = 'Natalie';
$_SESSION['logged_in'] = true;
if ($_SESSION['logged_in']) {
echo "Hello, " . $_SESSION['username'] . "! You are logged in.";
}
?>
6. Storing Session Data
<?php
session_start();
$_SESSION["username"] = "Natalie";
?>
7. Accessing & Unsetting
<?php
session_start();
echo $_SESSION["username"];
unset($_SESSION["username"]);
?>
8. Destroying Sessions
<?php
session_start();
session_destroy();
?>
9. Cookie Support Check
<?php
if (count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
This might also interest you
- What steps should be taken to troubleshoot and resolve issues with integrating the Google Places API in a WordPress environment?
- In what scenarios would storing different data types in a single array be beneficial in PHP development?
- In PHP, how can the search functionality be optimized to display all relevant recipe information, including ingredients, when searching for a specific ingredient like "Tomatoes"?