Lesson 4 of 8
Not started

Securing PHP Sessions with SSL

Securing PHP Sessions Over SSL

PHP sessions are a prime target for attackers. Without proper configuration, session cookies can be intercepted, leading to session hijacking. Here is how to lock them down.

Essential php.ini Settings

; Force cookies to be sent only over HTTPS
session.cookie_secure = 1

; Prevent JavaScript access to session cookies
session.cookie_httponly = 1

; Set SameSite attribute to prevent CSRF
session.cookie_samesite = "Strict"

; Use only cookies for sessions (no URL-based session IDs)
session.use_only_cookies = 1
session.use_trans_sid = 0

; Regenerate session ID to prevent fixation
session.use_strict_mode = 1

Setting Session Security in Code

If you cannot modify php.ini, configure sessions programmatically before calling session_start():

ini_set('session.cookie_secure', '1');
ini_set('session.cookie_httponly', '1');
ini_set('session.cookie_samesite', 'Strict');
ini_set('session.use_only_cookies', '1');
ini_set('session.use_trans_sid', '0');
ini_set('session.use_strict_mode', '1');

session_start();

Or use session_set_cookie_params():

session_set_cookie_params([
'lifetime' => 3600, // 1 hour
'path' => '/',
'domain' => 'yourdomain.com',
'secure' => true, // HTTPS only
'httponly' => true, // No JavaScript access
'samesite' => 'Strict', // CSRF protection
]);

session_start();

Session Regeneration

Regenerate the session ID after authentication to prevent session fixation attacks:

// After successful login
session_regenerate_id(true); // true = delete old session
$_SESSION['user_id'] = $userId;
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];

Session Validation

Validate session integrity on each request:

function validateSession(): bool {
if (!isset($_SESSION['user_id'])) return false;
if ($_SESSION['ip'] !== $_SERVER['REMOTE_ADDR']) return false;
if ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) return false;
return true;
}

Key Rules

  • Always set cookie_secure = 1 in production

  • Always set cookie_httponly = 1

  • Always regenerate session ID after login

  • Never pass session IDs in URLs

  • Consider shorter session lifetimes for sensitive apps