How to Defend Against CSRF Attacks in PHP
This article explains the principles of CSRF attacks and provides practical PHP techniques to prevent them, including token generation and verification, checking Referer and Origin headers, configuring secure cookie attributes, and ensuring safe login and logout processes.
1. Understanding CSRF Attack Mechanism
Before defending against CSRF attacks, it is important to understand that the attack exploits the victim's authenticated cookies to forge malicious requests that appear legitimate to the target site, requiring the victim to be logged in.
2. Generating and Verifying Tokens
To prevent CSRF, a random token tied to the user's session is stored on the server and added as a hidden field in each form. When the form is submitted, the token is compared with the server‑side value; mismatches indicate an illegal request.
Example code for token generation and verification:
<code>// Generate token
function generateToken() {
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;
return $token;
}
// Verify token
function verifyToken($token) {
if (isset($_SESSION['csrf_token']) && $_SESSION['csrf_token'] === $token) {
return true;
}
return false;
}
// Add token field to form
function addTokenField() {
$token = generateToken();
echo '<input type="hidden" name="csrf_token" value="' . $token . '">';
}
</code>3. Verifying Request Origin
Token verification alone may not be sufficient, so checking the request's Referer or Origin header adds another layer of protection.
Example code for verifying the Referer header:
<code>function verifyReferer() {
if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) {
return true;
}
return false;
}
</code>Example code for verifying the Origin header:
<code>function verifyOrigin() {
if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] === 'https://www.example.com') {
return true;
}
return false;
}
</code>4. Properly Setting Cookie Attributes
Configuring cookie attributes such as Secure and HttpOnly, limiting the cookie to HTTPS connections and the appropriate domain, makes CSRF attacks harder.
Example code for setting secure cookie parameters:
<code>session_set_cookie_params([
'lifetime' => 86400, // one day
'path' => '/',
'domain' => '.example.com',
'secure' => true, // only over HTTPS
'httponly' => true // inaccessible to JavaScript
]);
session_start();
</code>5. Securing Login and Logout Processes
During login, generate a login token stored in the session and verify it on each request. During logout, destroy the session data and delete the session ID to prevent reuse.
Summary
CSRF attacks are common web security threats, but by combining token generation and verification, checking Referer/Origin headers, setting strict cookie attributes, and handling login/logout securely, PHP applications can effectively protect users and data.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.