Current Location: Home> Latest Articles> Use session_register_shutdown() to strengthen defense against CSRF?

Use session_register_shutdown() to strengthen defense against CSRF?

M66 2025-06-06

Among the security protection of web applications, cross-site request forgery (CSRF) is one of the most common and widely affected attack methods. Although modern frameworks usually integrate CSRF protection mechanisms, protection policies need to be implemented manually for systems developed using native PHP. This article will explore how to enhance the consistency and security of sessions in CSRF defense with the help of the session_register_shutdown() function in PHP.

Introduction to CSRF Attack

CSRF (Cross-Site Request Forgery) attacks are when an attacker induces a user who has logged into a trusted website to send unintentional requests to the website without knowing it. This may lead to security issues such as user data being tampered with and sensitive operations being triggered.

Common defense methods include:

  • Use CSRF Token and Verify

  • Check the Referer or Origin header

  • Restrict request methods (such as forced POST)

  • Set SameSite Cookie Attribute

However, an important point of CSRF defense is often overlooked: the consistency control of session state. At this time, the session_register_shutdown() function can play a unique role.

What is session_register_shutdown()?

session_register_shutdown() is a function introduced in PHP 5.4 to automatically close session when script execution ends. This is similar to the traditional session_write_close() , but is safer and more reliable. It ensures that session data is automatically written and closed at the end of the script life cycle, avoiding problems that session data is not saved or overwritten in exceptional situations.

session_register_shutdown() and CSRF defense relationship

The danger of CSRF attacks is largely due to the ability of an attacker to perform sensitive operations using the user's existing sessions. If the session data is corrupted by malicious scripts or multiple concurrent requests, the defense mechanism may be bypassed.

Using session_register_shutdown() can help ensure:

  1. Session atomicity : Prevent session data race caused by concurrent execution of multiple requests.

  2. Prevent CSRF Tokens from losing : Ensure session writing before script termination and logical jumps (such as header redirection), thereby ensuring the reliability of CSRF Tokens.

  3. Enhance the stability of token rotation : Ensure that the session data will not be corrupted during the token update process, and improve the token's timeliness control ability.

Practical Examples

Suppose you use the CSRF Token mechanism on a form submission page, combined with session_register_shutdown() for strengthening:

 <?php
session_start();
session_register_shutdown();

// Initialize or verify CSRF Token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        die('CSRF Verification failed');
    }

    // Process form data
    // ...
}

// Generate form
?>
<form method="POST" action="https://m66.net/form-handler.php">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
    <input type="text" name="data">
    <input type="submit" value="submit">
</form>

In this example, even if the exit() , die() or HTTP jump statement appears in the middle of the code, the session can still be saved correctly at the end of the script because session_register_shutdown() is registered. In this way, the effectiveness of CSRF Token in logical processing is guaranteed.

Summarize

Although session_register_shutdown() is not a function designed for CSRF defense, in secure programming practice, it provides a way to write session data stably, thereby indirectly enhancing the reliability of the CSRF Token mechanism. Especially in Web applications where complex interactions such as multiple redirects, exception aborts, and concurrent requests cannot be ignored.

In this way, we not only achieve safer session control, but also provide a solid backing for the overall application's CSRF defense capabilities. Using PHP native mechanism to achieve security protection is an important step in improving application security.