PHP implements secure programming: CSRF attack and defense
In Internet applications, security issues have always been an important issue. Among them, Cross-Site Request Forgery (CSRF) attack is a common vulnerability and one that is easily exploited by attackers. So, how to implement secure programming in PHP development? This article will focus on CSRF attacks and defense solutions.
1. What is CSRF attack?
CSRF attack, cross-site request forgery, is an attack method that uses the victim's logged-in status to send malicious requests to the target website without the victim's knowledge. An attacker may obtain the victim's login status through various methods, and then initiate a forged request to the target website without being noticed, thereby carrying out the attack. The attacker may induce the victim to perform operations by allowing the victim to visit a third-party website, through links in emails or chat software, or by posting links on social networks, thereby triggering the attack.
In the following example, an attacker can let the victim visit a malicious website, generate a POST request, disguise it as a request from the target website, and obtain the permissions of the victim when he is logged in, that is, submit a comment:
<form action="https://www.targetwebsite.com/comment" method="post"> <input type="hidden" name="comment" value="harmful comment" /> <input type="submit" value="Submit Comment" /> </form> <script> document.forms[0].submit(); </script>
This attack method is very subtle, because the attacker does not attack the target website directly, but takes advantage of the vulnerabilities of the target website to achieve the attack. Since the victim is unaware, it is difficult to detect the attack. If the target website fails to prevent CSRF attacks, it may lead to data leakage, malicious operations and other risks.
2. How to defend against CSRF?
Since CSRF attacks are so dangerous, how to defend against them? The following are some common defense strategies:
1. Add token verification
When the user logs in, the backend server generates a token and sends it back to the front end, and saves the token to the server. In subsequent interactions with the server, the front end needs to bring the token to the server along with the request. The server can determine whether the request is legitimate through token verification.
The following is a simple code example:
<!-- 后端代码 --> <?php session_start(); if(!isset($_SESSION['token'])){ $_SESSION['token'] = md5(uniqid(rand(), true)); } $token = $_SESSION['token']; ?> <!-- 前端代码 --> <form method="post" action="/some/url"> <?php echo "<input type='hidden' name='token' value='".$token."' />"; ?> <input type="text" name="username" /> <input type="text" name="password" /> <input type="submit" value="Submit" /> </form>
In this example, we generate a random token in the background and pass it back to the front end. Next, the token is appended to the hidden input tag. When the front end submits a request, the token will also be submitted, and the code on the server will verify whether the request is legal based on the submitted token.
2. Add Referer verification
Referer is part of the HTTP header, which contains the page from which the user redirected to the current page. By checking the Referer in the HTTP header, the server can determine whether the request comes from a legitimate page. If the Referer is detected to be incorrect, the server will refuse to respond to the request.
The following is a simple code example:
<?php $referer = $_SERVER['HTTP_REFERER']; if(parse_url($referer, PHP_URL_HOST) != 'www.validwebsite.com') { die("Invalid Referer"); } // 处理正常的请求 ?>
In this example, we get the Referer in the HTTP header and check if the request comes from a website named "www.validwebsite.com" website. If the request does not come from this website, the server will reject the response and display an "Invalid Referer" message.
3. Add browser cookies
Cookie-based CSRF attack is an attack method that uses the user's login status and sends the user's cookie to the attacker's website. We can do this by setting a short-lived cookie for a sensitive page and then checking for the cookie's existence when performing actions related to that page.
The following is a simple code example:
header('Set-Cookie: csrf_cookie=' . uniqid(rand(), true) . '; path=/; HttpOnly');
In this example, we generated a random csrf_cookie and set it to HttpOnly, which means the cookie can only be passed through the HTTP protocol transfer, and cannot be accessed via JavaScript. When the request reaches the server, we can check if its cookie matches that page, identifying a possible attack.
Summary
CSRF attack is a very dangerous attack method. Defending against CSRF attacks not only helps protect data security, but is also a basic requirement for implementing secure programming. In the PHP development environment, we can take some measures to prevent CSRF attacks, such as setting token verification, Referer verification, adding browser cookies, etc. Through these measures, we can effectively protect user login states and pages involving sensitive data from attacks.
The above is the detailed content of PHP implements secure programming: CSRF attack and defense. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
