The rapid development of the Internet and increasingly complex user needs have made the requirements and functions of Web applications increasingly complex and diverse. However, this has also led to more and more prominent web security issues. One of the common attack methods is the cross-site request forgery (CSRF) attack.
Simply put, a CSRF attack means that an attacker uses the identity authentication of a legitimate user on a certain site to impersonate the user's identity and complete a certain task in the name of the user without the user's permission or knowledge. A way of attacking some operational behaviors. There are many common attack methods, such as sending malicious requests through URLs, iframes, pictures, etc. Setting HTTP Referer in the PHP form is an effective way to prevent CSRF attacks.
So, how to set HTTP Referer in PHP form?
HTTP Referer means that before sending a request, the browser will check the source address of the current page, that is, the source of the request. A request is considered legitimate if the source of the request is the same as the source address in the request received by the server. Therefore, by setting HTTP Referer, you can add a layer of protection to the form and limit the source address of form submission, thereby effectively preventing CSRF attacks.
The specific setting process is as follows:
1. Add the following code to the form page:
<?php session_start(); $token = md5(uniqid(rand(), TRUE)); $_SESSION['csrf_token'] = $token; ?> <form action="" method="post"> <input type="hidden" name="csrf_token" value="<?php echo $token; ?>"> //其他表单元素 <input type="submit" value="提交"> </form>
First, open the session in the form page, and then generate a random token As a CSRF token, store it in the session. Assign the token to a hidden element and submit it to the server along with the form as part of the form element.
2. Next, add the following code to the form processing page:
session_start(); if($_POST['csrf_token'] != $_SESSION['csrf_token']) { //不合法的请求 exit("非法请求!"); } //处理表单数据之前。...
In the form processing page, first open the session, and then compare the csrf_token in the form with the token previously stored in the session Compare. If the tokens are inconsistent, the submission is considered illegal and the handler ends. Otherwise, the form data can be processed normally.
In summary, setting HTTP Referer in a PHP form is not difficult. You only need to generate a random CSRF Token in the form page, save it in the session, and then compare the forms in the form processing page. The token in and the token in session are enough. This can effectively avoid cross-site request forgery attacks.
The above is the detailed content of How to set HTTP Referer in PHP form to prevent cross-site request forgery. For more information, please follow other related articles on the PHP Chinese website!