Home >Backend Development >PHP Tutorial >How to prevent impersonation of requests in php

How to prevent impersonation of requests in php

小云云
小云云Original
2018-05-19 17:00:582170browse

This article mainly shares with you how to prevent simulated requests in PHP. I hope it can help you.

1. Some websites use the method of detecting the density of logins from this IP address. After multiple logins, you need to enter a verification code. At this time, the submission of CURL simulation needs to analyze the verification code image, so that it will It takes a lot of time. Of course, this is to prevent the login from being exploded and user data leaked.

2. Another method is to save the generated random code directly in the session, and then place it in the hidden field of the input. This is much worse than the verification code.

3. Note that javascipt itself cannot be submitted across domains, not because it cannot be done, but to prevent others from maliciously stealing user information, such as clicking to open his website, using an iframe to open a regular web page, and then opening it in another Stealing in an iframe.

To achieve ajax cross-domain access, you need to set

header("Access-Control-Allow-Origin:*"); //跨域权限设置,允许所有

To prevent ajax cross-domain access, you need to set

header("Access-Control-Allow-Origin:http://www.test.com"); //只允许test.com跨域提交数据

4. If you want to prevent php For simulated requests, such as post requests, you can set it to be an ajax request before it can be processed.

//判断是否为ajax请求,防止别人利用curl的post抓取数据
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])&&strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ }

Complete solution:

header("Access-Control-Allow-Origin:http://leshen.applinzi.com/cet"); //只允许本站提交数据,前端防ajax跨域,其实js本来就不能跨域 

//判断是否为ajax请求,后端防止别人利用curl的post抓取数据
if(isset($_SERVER["HTTP_X_REQUESTED_WITH"])&&strtolower($_SERVER["HTTP_X_REQUESTED_WITH"])=="xmlhttprequest"){ 
    //处理业务逻辑
}else{ 
    echo "we caught you! you have no access!";
};

The above is the detailed content of How to prevent impersonation of requests in php. 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