Php

Sessions and cookies

What Are Cookies?

  • Cookies are small files stored in the user’s browser.

  • Used to remember information like login status, preferences, or shopping cart items.


✅ Setting a Cookie

php
setcookie("username", "Alice", time() + 3600); // Expires in 1 hour
  • setcookie(name, value, expire)

  • Must be called before any HTML output.

✅ Reading a Cookie

php
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Hello, guest!";
}

✅ Deleting a Cookie

php
setcookie("username", "", time() - 3600); // Expire it in the past

What Are Sessions?

  • Sessions store data on the server, not in the browser.

  • More secure than cookies.

  • Useful for login systems, shopping carts, and temporary user data.


✅ Starting a Session

php
session_start(); // Must be at the top of the file

✅ Storing Data in a Session

php
session_start();
$_SESSION["user"] = "Alice";

✅ Accessing Session Data

php
session_start();
echo $_SESSION["user"]; // Output: Alice

✅ Removing Session Data

php
session_start();
unset($_SESSION["user"]); // Remove a variable
session_destroy(); // End the entire session

Differences: Cookies vs Sessions

Feature Cookie Session
Stored Where? On client (browser) On server
Size Limit Small (~4KB) Larger (depends on server)
Security Less secure More secure
Expiry Manual control (time) Ends on browser close or logout
Use Case Remember preferences, IDs Login, shopping cart, temp data

Real Use Case: Login Flow

  1. User logs in → verify credentials

  2. Start session and store $_SESSION["user_id"]

  3. On other pages, check if $_SESSION["user_id"] exists

  4. Log out → session_destroy()


✅ Example

login.php

php
session_start();
$_SESSION["user"] = "Alice";
echo "Logged in!";

dashboard.php

php
session_start();
if (isset($_SESSION["user"])) {
echo "Welcome, " . $_SESSION["user"];
} else {
echo "Please log in first.";
}

Leave a Reply

Your email address will not be published. Required fields are marked *