Information Security 6 min read

How to Defend Against CSRF Attacks Using PHP

This article explains the fundamentals of CSRF attacks, how they exploit authenticated users' cookies, and provides practical PHP techniques—including token generation and verification, request‑origin checks, secure cookie settings, and safe login/logout handling—to effectively protect web applications.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Defend Against CSRF Attacks Using PHP

As web applications evolve and become ubiquitous, web security issues grow increasingly important, and Cross‑Site Request Forgery (CSRF) attacks have become a common threat. CSRF attacks involve an attacker impersonating a legitimate user’s request to perform malicious actions such as unauthorized transfers or password changes. To safeguard users and web applications, developers must adopt defensive measures; this article demonstrates how to use PHP to protect against CSRF attacks.

1. Understand the Principle of CSRF Attacks

Before defending against CSRF, it is essential to understand its mechanism. CSRF exploits the fact that a victim is already authenticated on a target site and has valid cookies. The attacker crafts a malicious request that the browser sends together with the victim’s cookies, making the request appear legitimate. Consequently, the victim must be an authenticated user for the attack to succeed.

2. Generate and Verify Tokens

To mitigate CSRF, a random token tied to the user’s session can be used to validate request legitimacy. The token is stored server‑side and inserted as a hidden field in each form. Upon submission, the server compares the submitted token with the stored value; a mismatch indicates an illegal request, which should be rejected.

Below is a sample implementation using PHP:

// 生成令牌
function generateToken() {
    $token = bin2hex(random_bytes(32));
    $_SESSION['csrf_token'] = $token;
    return $token;
}

// 验证令牌
function verifyToken($token) {
    if (isset($_SESSION['csrf_token']) && $_SESSION['csrf_token'] === $token) {
        return true;
    }
    return false;
}

// 在表单中添加令牌字段
function addTokenField() {
    $token = generateToken();
    echo '
';
}

3. Verify Request Origin

Token verification alone may not be sufficient because an attacker could obtain the token by other means. Additional protection can be achieved by checking the request’s origin via the Referer or Origin header.

Example code for verifying the Referer header:

function verifyReferer() {
    if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) {
        return true;
    }
    return false;
}

Example code for verifying the Origin header:

function verifyOrigin() {
    if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] === 'https://www.example.com') {
        return true;
    }
    return false;
}

4. Properly Set Cookie Attributes

Enhancing security can also be achieved by configuring cookie attributes to make CSRF attacks harder. Cookies should be sent only over HTTPS, limited to the appropriate domain, and marked as HttpOnly. The following code demonstrates setting these attributes in PHP:

session_set_cookie_params([
    'lifetime' => 86400, // one day
    'path' => '/',
    'domain' => '.example.com',
    'secure' => true,   // transmit only over HTTPS
    'httponly' => true   // inaccessible to JavaScript
]);
session_start();

5. Pay Attention to Login and Logout Security

Login and logout are critical operations that must be protected. During login, generate a login token stored both in the server session and the client form, and verify it on each login request. During logout, destroy the user’s session data and delete the session ID to prevent attackers from reusing it.

Conclusion

CSRF attacks are a prevalent web security issue, but by employing PHP‑based defenses such as token generation and verification, request‑origin checks, secure cookie configurations, and careful handling of login/logout processes, developers can effectively protect their applications and users from this threat.

PHPCSRFtokenWeb Securitypreventive measures
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.