Home page >> Website source code >>Body

PHP prohibits specifying IP access or calling code

Author: A little Jack    Time: 2024-01-13 11:31:11    Browse: 220   

PHP prohibits specifying IP access or calling code from Care blog , save the IP to be blackened one by one in the ip.txt line, and the blackened IP cannot be accessed or called, or can be expanded by itself when jumping or denying access

Note: Please create an ip.txt manually, or an error will be reported.

The codes are as follows:

 <? Php//Get Visitor IP     $visitor_ip = $_SERVER['REMOTE_ADDR'];     $blacklist_file = 'ip.txt';     $blacklisted_ips = file($blacklist_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);// Check whether the IP is in the ip.txt blacklist     if (in_array($visitor_ip, $blacklisted_ips)) { //IP is in the blacklist, access is denied     header('HTTP/1.1 403 Forbidden');     echo 'Access Denied';     exit; }//Normal code if not in the blacklist. ?>

If you use CDN, you may get the node IP with the above code. You can use the following code to solve the problem.

 <? Php//uses CDN for you to obtain user IP     $visitor_ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ??  $_SERVER['HTTP_X_FORWARDED_FOR'] ??  $_SERVER['REMOTE_ADDR'];     $blacklist_file = 'ip.txt';     $blacklisted_ips = file($blacklist_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);     if (in_array($visitor_ip, $blacklisted_ips)) { //IP is in the blacklist, access is denied     header('HTTP/1.1 403 Forbidden');     echo 'Access Denied';     exit; }//Code allowed to access ?>

Reprint the code, although its generation is missing, the function is available, and it can be used as a case reference for young partners!


Text label: Care blog   IP   Disable IP   IP access  
 A little Jack

A little Jack https://lkba.cn

The blogger focuses on Z-Blog website construction, website optimization, computer troubleshooting, reinstallation, optimization, maintenance system, etc, QQ/WX: 2126245521 (please specify the purpose)

Related articles

Previous:

Next:

No comment for this article - Welcome

 Please fill in the verification code

Processed : 0.048 SQL : 14