Home > Article > Backend Development > How to implement access ban in php
php method to implement access prohibition: 1. Create a php sample file; 2. Pass "if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {. ..}" method to implement IP access restrictions.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
How to implement access ban in php?
Restrict ip segment access and prohibit ip submission form in php
In project applications, we often need to restrict ip segment access or restrict IP submission Forms and other IP-related functions, today I will share the code I use, I hope it will be helpful to everyone
Just add the following code to the page where you need to prohibit access or submit the form to make a judgment. .
Note: The following is just an example code of PHP restricting IP. If you plan to apply it to CMS, please modify it yourself.
<?php /加IP访问限制 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) { $userip = getenv('HTTP_CLIENT_IP'); } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) { $userip = getenv('HTTP_X_FORWARDED_FOR'); } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) { $userip = getenv('REMOTE_ADDR'); } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) { $userip = $_SERVER['REMOTE_ADDR']; } //限制ip if ($userip=='192.168.1.88'){ header("location:http://t.qq.com/wb631992791");//被禁止后跳转到微博 exit; } //限制ip段 $ip_arr = explode('.', $userip); #限制的ip段,假设是192.168.*.* if (!(($ip_arr[0] == '192' && $ip_arr[1]=='168') )){ header("location:http://t.qq.com/wb631992791");//被禁止后跳转到微博 exit; }else{ header("location:http://afish.cnblogs.com");//正常IP则直接访问小鱼阁首页 exit; } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to implement access ban in php. For more information, please follow other related articles on the PHP Chinese website!