search
HomeBackend DevelopmentPHP TutorialPHP 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!

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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools