Home >Backend Development >PHP Problem >How to ban a region ip in php

How to ban a region ip in php

藏色散人
藏色散人Original
2020-08-15 11:06:393260browse

How to implement prohibition of a region in php: first use a variable to save the visitor's IP address; then obtain the detailed information of the IP address from the outside world; then determine whether it is within the province that denies access; and finally make corresponding actions Just respond.

How to ban a region ip in php

Recommendation: "PHP Video Tutorial"

PHP bans IPs in a certain area

Before, the blog banned IP access from the entire Jiangsu Province

In the backend, PHP is actually used to determine the IP source of the visitor and handle it accordingly

Some common syntax of PHP will be used in actual combat:

Conditional judgment

Loop

Array

Super global variable

In addition, some functions that come with the system will also be used

Let’s talk about the specific ideas:

1. Use a variable to save the visitor’s IP address

2. Obtain detailed information of the IP address from the outside world

3. Determine whether it is within the province that denies access

4. Make corresponding response

The first is to save the visitor's IP. You can use the super global variable $_SERVER to obtain the visitor's IP address.

$ip = $_SERVER['REMOTE_ADDR'];

Use an array to save the provinces that are prohibited from access.

$verification = array("xx省", "xx省", ...);

Use the Taobao IP library and add the Taobao IP library to the (Provincial accuracy exceeds 99.8%, city accuracy exceeds 96.8%) All information in the page is saved in a string

$result = file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip=".$ip);

Among them, the file_get_contents() function saves all strings in a file in In a string

In the web page, PHP displays the final code return value instead of displaying the PHP code, which is different from the front end

It is difficult to save it in a string Use it for comparison directly, so to process the string, it is best to turn it into a variable

$ipInformation = json_decode($result, true);

json_decode() function converts a string in JSON form into a PHP variable, here it is converted into a two-dimensional association Array

$address['data']['region'] returns the Chinese province of the IP

Finally, loop and conditional judgment are used to process the access denial

The final code :

Among them, TODO is how you handle IPs within the range. For example, you can directly die(); to disable page display

The above is the detailed content of How to ban a region ip 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