Current Location: Home> Latest Articles> Use init functions to make security settings (such as preventing XSS and CSRF)

Use init functions to make security settings (such as preventing XSS and CSRF)

gitbox 2025-05-28

In web development, security is always a key issue for developers. With the continuous escalation of attack methods, XSS (cross-site scripting attack) and CSRF (cross-site request forgery) have become the two most common forms of attack. Therefore, reasonable security configuration is the key to preventing such attacks. As a widely used programming language, PHP provides a rich way to set up security. This article will explore how to effectively prevent XSS and CSRF attacks through the security configuration of the init function.

What are XSS and CSRF attacks?

XSS attack (cross-site scripting attack)

XSS refers to an attacker inserting malicious JavaScript code into a web page to induce users to execute these malicious codes, thereby stealing users' sensitive information (such as cookies, session data, etc.). XSS attacks can execute malicious scripts in unauthorized users' browsers, causing information leakage and abuse.

CSRF attack (cross-site request forgery)

CSRF attacks are when an attacker induces logged-in users to access malicious websites, thereby initiating unauthorized requests without the user's knowledge. In this way, the attacker can use the victim's identity to perform various operations (such as changing passwords, transferring money, etc.).

Secure settings through init function

In PHP, we can effectively prevent XSS and CSRF attacks by making global security settings in the init function. The init function is usually executed during the initialization of the application and is an ideal place to set up the application configuration and handle global security measures.

Prevent XSS attacks

  1. Output encoding:

    Any data input from a user should be encoded in HTML when output to the page. This prevents malicious JavaScript code entered by the user from being executed by the browser.

     function init() {
        // Set the default output encoding,prevent XSS attack
        ini_set('html_errors', 0);
    }
    
    // Perform when outputting user data HTML Entity encoding
    function safeOutput($data) {
        return htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    }
    
    // Example:Output content input by the user
    echo safeOutput($_GET['user_input']);
    

    In the above code, the htmlspecialchars function escapes special characters (such as < , > , & , etc.) from user input to HTML entities, avoiding the browser parsing it into HTML or JavaScript code.

  2. Disable inline JavaScript:

    Some browsers may allow the execution of inline JavaScript code, although the user's input has been escaped. Therefore, in order to further strengthen protection, the execution of inline scripts can be prevented through HTTP headers.

     function init() {
        // set up Content Security Policy(CSP)Header information,Restrict the source of scripts
        header("Content-Security-Policy: script-src 'self' https://gitbox.net;");
    }
    

    In the above code, we limit the source of the script by setting the Content-Security-Policy header information, and only allow JavaScript scripts to be loaded from the current domain name and gitbox.net to avoid the loading of external malicious scripts.

Prevent CSRF attacks

  1. Generate and verify CSRF Token:

    The key to a CSRF attack is to forge requests. By using CSRF Token, attackers can effectively prevent forgers from making requests. Each time a user visits a page, the server generates a unique CSRF token and embeds it into the form. When the form is submitted, the server verifies whether the token matches the token in the user session, thereby confirming the legitimacy of the request.

     function generateCSRFToken() {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        if (empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }
    
    function verifyCSRFToken($token) {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        if (empty($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']) {
            die('CSRF token validation failed');
        }
    }
    

    In the form, generate the CSRF Token and submit it as a hidden field:

     // generate Token
    $csrfToken = generateCSRFToken();
    ?>
    
    <form method="POST" action="https://gitbox.net/submit_form.php">
        <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
        <!-- Other form fields -->
        <input type="submit" value="Submit">
    </form>
    

    When the form is submitted, the server verifies whether the csrf_token in the request is consistent with the token stored in the session to ensure the legitimacy of the request.

  2. Check the Referer header:

    CSRF attacks usually rely on users to make cross-site requests while logged in. You can further reduce the risk of CSRF attacks by checking the Referer header in the request to ensure that the request comes from a trusted page.

     function checkReferer() {
        $referer = $_SERVER['HTTP_REFERER'] ?? '';
        if (empty($referer) || strpos($referer, 'gitbox.net') === false) {
            die('Invalid referer');
        }
    }
    

Summarize

By making appropriate security configuration in the init function, we can effectively prevent XSS and CSRF attacks. Output encoding, setting up Content Security Policy, generating and verifying CSRF Tokens, and checking Referer top measures are effective ways to protect against these attacks. Hopefully, the examples and best practices provided in this article will help you build more secure PHP applications that protect users from potential security threats.