Sessions and Cookies
## Learning Objectives
- Understand PHP sessions
- Work with session data
- Set and read cookies
- Implement session security
## Sessions
### How Sessions Work
1. User visits site
2. Server creates unique session ID
3. Session ID stored in cookie OR passed via URL
4. Server uses session ID to retrieve session data
5. Data persists across page requests
### Starting a Session
```php
```
### Session Status
```php
```
## Session Data
### Storing Data
```php
'dark',
'language' => 'en'
];
echo "Session data stored";
?>
```
### Reading Data
```php
```
### Checking Session Data
```php
```
### Removing Data
```php
```
### Flash Messages
```php
```
## Session Configuration
### php.ini Settings
```ini
session.save_handler = files
session.save_path = "/var/lib/php/sessions"
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
session.gc_maxlifetime = 3600
```
### ini_set()
```php
3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
session_start();
?>
```
### Regenerate Session ID
```php
$interval) {
session_regenerate_id(true);
$_SESSION['last_regeneration'] = time();
}
}
?>
```
## Cookies
### Setting Cookies
```php
time() + (30 * 24 * 60 * 60),
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
?>
```
### Cookie Parameters
| Parameter | Description |
|-----------|-------------|
| expires | Unix timestamp for expiration |
| path | Path on domain where cookie is available |
| domain | Domain for cookie |
| secure | Only send over HTTPS |
| httponly | Not accessible via JavaScript |
| samesite | 'Strict', 'Lax', or 'None' |
### Reading Cookies
```php
```
### Modifying Cookies
```php
```
### Deleting Cookies
```php
time() - 3600,
'path' => '/',
'domain' => 'example.com',
'secure' => true,
'httponly' => true
]);
// Unset from $_COOKIE
unset($_COOKIE['username']);
?>
```
## Cookie Arrays
### Setting Array Cookie
```php
'dark',
'language' => 'en',
'notifications' => true
];
setcookie("preferences", json_encode($preferences), time() + (30 * 24 * 60 * 60));
?>
```
### Reading Array Cookie
```php
```
## Session vs Cookies
| Feature | Sessions | Cookies |
|---------|----------|---------|
| Storage | Server | Browser |
| Capacity | Large (unlimited) | Small (~4KB per cookie) |
| Security | More secure (no data in browser) | Less secure (exposed to client) |
| Lifespan | Until session expires | Until expiration |
| Performance | Slower (server read) | Faster (client read) |
## Practical Examples
### User Login
```php
```
### Authenticated Page
```php
$timeout)) {
session_unset();
session_destroy();
header("Location: login.php?error=timeout");
exit;
}
// Update last activity
$_SESSION['last_activity'] = time();
// Show page content
echo "Welcome, " . htmlspecialchars($_SESSION['username']);
?>
```
### User Logout
```php
```
### Remember Me (Cookie)
```php
```
```php
time() + (30 * 24 * 60 * 60),
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Strict'
]);
}
?>
```
## Security Best Practices
### Session Security
```php
```
### Cookie Security
```php
time() + (30 * 60),
'path' => '/',
'domain' => '',
'secure' => true, // HTTPS only
'httponly' => true, // No JavaScript access
'samesite' => 'Strict' // CSRF protection
]);
// Sensitive data: use session instead of cookie
// Never store passwords in cookies
?>
```
### CSRF Protection
```php
```
```php
```
## Summary
- `session_start()` begins a session (must be before output)
- `$_SESSION` array stores session data
- `session_destroy()` destroys the session completely
- `session_regenerate_id()` creates new session ID
- `setcookie()` sends cookie header (before any output)
- `$_COOKIE` array contains cookie values
- Sessions store data server-side; cookies store data client-side
- Always use secure cookie settings: `httponly`, `secure`, `samesite`
- Regenerate session ID after login
- Implement session timeout for security
- Use CSRF tokens for form protection
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →