Home  >  Article  >  Backend Development  >  How to protect PHP functions from CSRF attacks?

How to protect PHP functions from CSRF attacks?

WBOY
WBOYOriginal
2024-05-01 14:39:01362browse

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.

如何防止 PHP 函数受到 CSRF 攻击?

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.

  1. Generate token:
Create a unique and hard-to-guess token and store it in a session or cookie.

<?php
session_start();

// 生成令牌并将其存储在会话中
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>

  1. Include the token in the form:
In the form you want to protect, include the token as a hidden field.

<form action="change_password.php" method="post">
  <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
  <!-- 其他表单字段 -->
</form>

  1. Validation Token:
When processing a form submission, verify that the token matches the token stored in the session or cookie. If there is no match, the request is rejected.

<?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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn