đź”´ What Happens If Attacker Gets Session ID?
Attacker copies your cookie value:
PHPSESSID=3cb3b25e0a6b8f9c0d7
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
- 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);
→ ensures the cookie is only sent over HTTPS.
- HttpOnly Flag
- Prevents JavaScript (like in XSS attacks) from reading the cookie.
ini_set('session.cookie_httponly', 1);
- Regenerate Session ID
- Regenerate the session ID on login or after privilege escalation:
session_regenerate_id(true);
→ Makes old IDs useless, preventing fixation.
- 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!");
}
⚠️ Note: Binding to IP may break sessions if users are on mobile networks (IP changes frequently).
- Short Session Lifetime
- Reduce how long a session is valid:
ini_set('session.gc_maxlifetime', 1800); // 30 minutes
- 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();
- SameSite Cookies
Protect against CSRF (Cross-Site Request Forgery).
In php.ini or code:
ini_set('session.cookie_samesite', 'Strict');
- 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)