Home > Article > Backend Development > How to protect PHP functions from CSRF attacks?
Summary: CSRF attacks in PHP functions can be defended by using tokens: generate a unique token and store it in the session or cookie. Include the token as a hidden field in the protected form. When processing form submission, verify that the token matches the stored token. If there is no match, the request is rejected.
How to defend against CSRF attacks in PHP functions
Cross-site request forgery (CSRF) is a malicious technique that allows The attacker sends spoofed requests through the victim's browser. For PHP applications, this could allow an attacker to perform unauthorized operations using certain functions.
Practical case:
Suppose you have a PHP application that contains a function change_password
that allows users to change their passwords. The function uses the following code:
<?php if (isset($_POST['password'])) { $password = $_POST['password']; // 更新数据库中的密码... } ?>
This code is vulnerable to a CSRF attack because an attacker can send a POST request to the victim's browser containing the password# they wish to use for the victim's password. ## Parameters. This attack can be accomplished through spoofed emails, malicious websites, or other methods.
Defense measures:
In order to defend against CSRF attacks, a mechanism needs to be implemented to verify the authenticity of the request. One common method is to use tokens.<?php session_start(); // 生成令牌并将其存储在会话中 $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); ?>
<form action="change_password.php" method="post"> <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" /> <!-- 其他表单字段 --> </form>
<?php if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) { // 令牌验证失败,拒绝请求 exit('Invalid request'); } ?>By implementing these defenses, you can reduce your PHP application's risk of CSRF attacks.
The above is the detailed content of How to protect PHP functions from CSRF attacks?. For more information, please follow other related articles on the PHP Chinese website!