About Lesson
PHP $_SESSION and $_COOKIE
Web applications need a way to store information about users while they navigate pages. HTTP is stateless, which means each request is independent and does not remember previous requests.To handle this, PHP provides:
- Sessions – server-side storage of user data.
- Cookies – client-side storage of user data in the browser.
PHP Sessions
A session is a way to store information (variables) on the server for a specific user across multiple pages.
Key points:
- Stored on server.
- Identified using a unique session ID (sent via cookie
PHPSESSID
or URL). - Can store sensitive data securely because it’s on server, not client.
- Automatically expires after a set time (default 24 minutes in PHP).
1. Starting a session:
PHP
<?php
session_start(); // Start a session or resume the existing one
// Set session variables
$_SESSION['username'] = "JohnDoe";
$_SESSION['email'] = "john@example.com";
echo "Session variables are set.";
?>
2. Accessing session variables on another page:
PHP
<?php
session_start(); // Always start the session first
echo "Username: " . $_SESSION['username'];
echo "Email: " . $_SESSION['email'];
?>
3. Destroying a session (logout):
PHP
<?php
session_start();
// Unset all session variables
session_unset();
// Destroy the session
session_destroy();
echo "Session destroyed. User logged out.";
?>
PHP Cookies
A cookie is a small file stored on the user’s browser containing information about the user.
Key points:
- Stored on client-side.
- Can store user preferences or authentication tokens.
- Set with an expiration time (otherwise it disappears when browser closes).
- Less secure than sessions (user can modify it).
1. Setting a cookie:
PHP
<?php
// Set a cookie named "user" with value "John" for 1 day
setcookie("user", "John", time() + 86400); // 86400 seconds = 1 day
echo "Cookie has been set.";
?>
2. Accessing a cookie:
PHP
<?php
if(isset($_COOKIE['user'])){
echo "User is: " . $_COOKIE['user'];
} else {
echo "Cookie is not set.";
}
?>
3. Deleting a cookie:
PHP
<?php
setcookie("user", "", time() - 3600); // Set expiration in past
echo "Cookie deleted.";
?>
Difference Between Session and Cookie:
Feature | Session | Cookie |
---|---|---|
Storage | Server | Client (Browser) |
Security | More secure | Less secure |
Lifetime | Until browser closed or destroyed | Can persist based on expiry |
Size Limit | Can store large data | Max 4KB |
Speed | Slightly slower (server access) | Faster (client access) |