Home > Article > Backend Development > PHP Framework Security Guide: How to Prevent CSRF Attacks?
A cross-site request forgery (CSRF) attack is a type of network attack in which an attacker tricks a user into performing unintended actions within the victim's web application.
CSRF attacks exploit the fact that most web applications allow requests to be sent between different pages within the same domain name. The attacker creates a malicious page that sends requests to the victim's application, triggering unauthorized actions.
1. Use anti-CSRF tokens:
// 生成令牌并存储在会话中 $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // 在表单中包含隐藏字段 <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>"> // 验证提交的令牌 if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) { // 令牌无效,拒绝请求 }
2. Use the Synchronizer Token Pattern:
// 在首次加载页面时生成令牌并存储在 Cookie 中 setcookie('csrf_token', bin2hex(random_bytes(32)), time() + 3600, '/'); // 在表单提交时,将令牌作为 HTTP 头发送 $headers = getallheaders(); $csrf_token = $headers['X-CSRF-Token']; // 验证提交的令牌 if (!isset($csrf_token) || $csrf_token !== $_COOKIE['csrf_token']) { // 令牌无效,拒绝请求 }
For example, preventing CSRF attacks on fund transfers in wallets:
// 在用户加载转账页面时生成令牌 $transfer_token = bin2hex(random_bytes(32)); // 在表单中包含隐藏字段 <input type="hidden" name="transfer_token" value="<?php echo $transfer_token; ?>"> // 验证提交的令牌 if (!isset($_POST['transfer_token']) || $_POST['transfer_token'] !== $transfer_token) { // 令牌无效,拒绝转账请求 }
By implementing these measures, you can Effectively prevent CSRF attacks and protect your PHP applications.
The above is the detailed content of PHP Framework Security Guide: How to Prevent CSRF Attacks?. For more information, please follow other related articles on the PHP Chinese website!