DEV Community

Cover image for PHP Session Security
Ahmed Raza Idrisi
Ahmed Raza Idrisi

Posted on

PHP Session Security

đź”´ What Happens If Attacker Gets Session ID?

Attacker copies your cookie value:

PHPSESSID=3cb3b25e0a6b8f9c0d7

Enter fullscreen mode Exit fullscreen mode
  • He sets this cookie in his own browser (via DevTools, extensions, or script).

  • On the next request, PHP sees that session ID and loads the victim’s session file.

  • âś… Attacker is logged in as you → they can do anything you can do.

This is why session security is critical.

🛡 How to Defend Against Session Hijacking

  1. Use HTTPS (TLS)
  • If you use plain HTTP, session cookies can be sniffed with tools like Wireshark.

  • Always enforce HTTPS and set:

ini_set('session.cookie_secure', 1);

Enter fullscreen mode Exit fullscreen mode

→ ensures the cookie is only sent over HTTPS.

  1. HttpOnly Flag
  • Prevents JavaScript (like in XSS attacks) from reading the cookie.
ini_set('session.cookie_httponly', 1);

Enter fullscreen mode Exit fullscreen mode
  1. Regenerate Session ID
  • Regenerate the session ID on login or after privilege escalation:
session_regenerate_id(true);

Enter fullscreen mode Exit fullscreen mode

→ Makes old IDs useless, preventing fixation.

  1. Bind Session to Client Properties
  • Check IP address, user-agent, etc. Example:
session_start();

$fingerprint = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR']);

if (!isset($_SESSION['fingerprint'])) {
    $_SESSION['fingerprint'] = $fingerprint;
} elseif ($_SESSION['fingerprint'] !== $fingerprint) {
    session_destroy();
    die("Session hijack attempt detected!");
}

Enter fullscreen mode Exit fullscreen mode

⚠️ Note: Binding to IP may break sessions if users are on mobile networks (IP changes frequently).

  1. Short Session Lifetime
    • Reduce how long a session is valid:
ini_set('session.gc_maxlifetime', 1800); // 30 minutes

Enter fullscreen mode Exit fullscreen mode
  • implement idle timeout:
if (!isset($_SESSION['last_activity'])) {
    $_SESSION['last_activity'] = time();
} elseif (time() - $_SESSION['last_activity'] > 900) { // 15 mins
    session_destroy();
    die("Session expired.");
}
$_SESSION['last_activity'] = time();

Enter fullscreen mode Exit fullscreen mode
  1. SameSite Cookies
  • Protect against CSRF (Cross-Site Request Forgery).

  • In php.ini or code:

ini_set('session.cookie_samesite', 'Strict');

Enter fullscreen mode Exit fullscreen mode
  1. Store Sensitive Data Outside Sessions
  • Don’t keep passwords, tokens, or critical secrets in $_SESSION.

  • Only store user IDs, roles, etc. → if hijacked, attacker still has limited info.

Top comments (0)