Home > Dev > PHP Security > Secure Session Handling

Secure Session Handling

This code enhances session security by setting proper session parameters and regenerating session IDs.

// Start secure session
function start_secure_session() {
    $session_name = 'secure_session_id';
    $secure = true; // Set to true if using https
    $httponly = true;

    ini_set('session.use_only_cookies', 1);
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params(
        $cookieParams["lifetime"], 
        $cookieParams["path"], 
        $cookieParams["domain"], 
        $secure, 
        $httponly
    );
    session_name($session_name);
    session_start();
    session_regenerate_id(true); // Regenerate session, delete the old one
}

// Usage
start_secure_session();
Back