Sessions in PHP (Login Memory Explained)
Understand sessions with a clear mental model and build a basic login memory flow.
Sessions allow your website to remember a user across pages.
The mental model
- Browser sends request - Server creates a session (a storage area) - Browser stores only a session id (usually in a cookie) - Each next request sends that id back - Server uses it to find the user’s stored data
```mermaid flowchart LR A[Browser] -->|Request| B[Server] B -->|Set session id cookie| A A -->|Next request with session id| B B -->|Load session data| C[Session Storage] ```
Step 1: Start session
Always call `session_start()` at the top before output:
```php <?php session_start(); ?> ```
Step 2: Store session values (like after login)
```php $_SESSION['user_id'] = 10; $_SESSION['name'] = 'Jessica Miller'; ```
Step 3: Read session values
```php if (isset($_SESSION['user_id'])) { echo "Welcome " . $_SESSION['name']; } ```
Step 4: Logout
```php session_start(); session_unset(); session_destroy(); ```
> Next: Cookies in PHP and how they differ from sessions.