htmlspecialchars() is a function used to prevent XSS (Cross-Site Scripting) attacks. Its role is to convert special characters in HTML (such as <, >, ", &) into HTML entities, preventing malicious scripts submitted by users from executing on the page. For example:
<?php
$user_input = '<script>alert("XSS")</script>';
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
?>
Output result:
<script>alert("XSS")</script>
This code effectively prevents the injection of malicious JavaScript into HTML, but it has little to no direct relation to defending against CSRF attacks.
CSRF exploits the user's "logged-in state." An attacker tricks the user into clicking a link or visiting an image/iframe, leveraging the user's current login session on a website to initiate a request. For example:
<img src="https://m66.net/delete_account.php" />
If the user is logged into m66.net and the server does not perform any validation, this request might actually delete the user's account.
The key to this attack is: the user unknowingly triggers a state-changing request, and the server trusts this request.
htmlspecialchars() operates at the "output stage," mainly preventing browsers from parsing malicious scripts. In contrast, CSRF attacks are initiated automatically or induced by the user's browser, and they can be triggered even if the page produces no output.
In other words, CSRF is a "request impersonating the user," which has no relation to whether output content is escaped. Therefore, htmlspecialchars() cannot prevent CSRF attacks.
Use CSRF Tokens
The most effective way is to add a randomly generated CSRF token in the form and validate it when processing requests. For example:
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>
<form method="POST" action="https://m66.net/update_profile.php">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<!-- Other form fields -->
<button type="submit">Submit</button>
</form>
<?php
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die("Illegal request!");
}
// Perform update operation
}
?>
Verify the Referer or Origin Header
Although not completely reliable, in some scenarios, this can help verify the legitimacy of a request. For example:
<?php
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if (parse_url($referer, PHP_URL_HOST) !== 'm66.net') {
die("Invalid origin");
}
?>
Use the SameSite Cookie Attribute
Modern browsers support preventing third-party requests from carrying cookies by setting the SameSite=Strict or SameSite=Lax cookie attributes:
setcookie('session_id', $value, [
'samesite' => 'Strict',
'secure' => true,
'httponly' => true
]);