What is CSRF and how to prevent it in PHP?
CSRF (Cross Site Request Forgery) is an attack where another website makes the browser of a logged-in user send a request to your site, without the user knowing. Because the browser sends the login cookie automatically, your site thinks the request is real.
How to prevent it: put a secret random token in every form, and check it when the form is submitted.
<?php
session_start();
// When showing the form: create the token
if (empty($_SESSION["csrf_token"])) {
$_SESSION["csrf_token"] = bin2hex(random_bytes(32));
}
?>
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION["csrf_token"]; ?>">
<?php
session_start();
// When the form is submitted: check the token
$token = $_POST["csrf_token"] ?? "";
if (!hash_equals($_SESSION["csrf_token"] ?? "", $token)) {
http_response_code(403);
exit("Invalid request.");
}
?>
- Use
hash_equals()to compare the tokens. - Set the session cookie with
SameSite=Laxor Strict. - Use POST (not GET) for actions that change data.
See the full steps in PHP Security Tips.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |