9. Cookies & Sessions (PHP)

🔹 1. Cookies in PHP

✅ What is a Cookie?

A cookie is a small piece of data stored in the user’s browser.

👉 Used for:

  • Remember login
  • User preferences (theme, language)
  • Tracking users

🔸 Creating Cookies

Use setcookie() function.

setcookie(name, value, expire, path, domain, secure, httponly);

Example:

setcookie("username", "Aditya", time() + 3600, "/"); // expires in 1 hour

Access Cookie:

echo $_COOKIE['username'];

🔸 Deleting Cookies

To delete a cookie, set its expiration time in the past.

setcookie("username", "", time() - 3600, "/");

⚠️ Important Notes:

  • Must call setcookie() before HTML output
  • Cookies are stored in browser (not secure for sensitive data)

🔹 2. Sessions in PHP

✅ What is a Session?

A session stores data on the server, not in the browser.

👉 Used for:

  • Login authentication
  • Shopping cart
  • User data across pages

🔸 Start Session

session_start();

👉 Must be at the top of the page


🔸 Store Session Data

$_SESSION['user'] = "Aditya";

🔸 Access Session Data

echo $_SESSION['user'];

🔸 Destroy Session

Destroy all session data:

session_start();
session_destroy();

Remove specific session:

unset($_SESSION['user']);

🔐 Session Security (Very Important)

If you ignore this, your website can be hacked easily.


🔸 1. Regenerate Session ID

Prevents session hijacking.

session_regenerate_id(true);

👉 Use after login


🔸 2. Use HTTPS

  • Always use SSL (https://)
  • Prevents data theft

🔸 3. Set Session Timeout

if (isset($_SESSION['last_activity']) && 
(time() - $_SESSION['last_activity'] > 1800)) {
session_unset();
session_destroy();
}
$_SESSION['last_activity'] = time();

👉 Auto logout after 30 minutes


🔸 4. Use Secure Cookie Settings

session_set_cookie_params([
'lifetime' => 0,
'path' => '/',
'secure' => true, // HTTPS only
'httponly' => true, // no JS access
'samesite' => 'Strict' // prevent CSRF
]);
session_start();

🔸 5. Validate User Agent (Advanced)

if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']) {
session_destroy();
}

🔁 Cookies vs Sessions

FeatureCookies 🍪Sessions 🔐
StorageBrowserServer
SecurityLess secureMore secure
Size Limit~4KBLarge
ExpirySet manuallyEnds on browser close (default)

✅ Real Example (Login System)

session_start();// login success
$_SESSION['user'] = "Aditya";// check login
if(isset($_SESSION['user'])){
echo "Welcome " . $_SESSION['user'];
} else {
echo "Please login";
}