Welcome to our tutorial on PHP Cross-Site Request Forgery (CSRF)! In this comprehensive guide, we'll dive deep into understanding CSRF, its implications, and how to protect your PHP applications from it. Let's get started!
Cross-Site Request Forgery is a type of attack that tricks the user into submitting unintended commands on a web application. The attacker exploits the trust a user has for a site by using a malicious site to perform actions on the user's behalf.
Imagine you're logged into your banking website. An attacker crafts a malicious link and sends it to you. Since you're already logged in, clicking the link may execute an unintended action on the banking site, such as transferring funds, changing passwords, etc.
When a user visits a site and performs an action, the web application generates a form containing sensitive data (like session tokens) and sends it to the server upon form submission. In a CSRF attack, an attacker tricks the user into loading a malicious page containing a form that matches the original form structure. This results in the browser sending the form data to the attacker's server, which then forwards it to the victim's site, causing unintended actions.
To protect against CSRF attacks, you can use the following methods:
// Generate token
$token = sha1(uniqid(mt_rand(), true));
$_SESSION['csrf_token'] = $token;
// In form
<input type="hidden" name="csrf_token" value="<?php echo $token; ?>">
// Verification
if (isset($_POST['csrf_token']) && isset($_SESSION['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// Valid request
} else {
// Invalid request (CSRF attack)
}// In login script
setcookie('csrf_token', sha1(uniqid(mt_rand(), true)), time() + (86400 * 30)); // 30 days expiration
// In form
<input type="hidden" name="csrf_token" value="<?php echo $_COOKIE['csrf_token']; ?>">
// Verification
if (isset($_COOKIE['csrf_token']) && isset($_POST['csrf_token']) && $_COOKIE['csrf_token'] === $_POST['csrf_token']) {
// Valid request
} else {
// Invalid request (CSRF attack)
}What is Cross-Site Request Forgery (CSRF)?
With this tutorial, you now have a good understanding of CSRF and how to protect your PHP applications from it. Happy coding! π‘π―