Home  >  Article  >  Backend Development  >  PHP restricts IP access to only allow access from specified IP addresses

PHP restricts IP access to only allow access from specified IP addresses

WBOY
WBOYOriginal
2016-07-25 08:54:421900browse
  1. /**

  2. * Check whether the accessed IP is a specified allowed IP
  3. * Enter description here...
  4. */
  5. function check_ip(){
  6. $ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168 .2.49');
  7. $IP=getIP();
  8. $check_ip_arr= explode('.',$IP);//Split the IP to be detected into an array
  9. #Restrict IP
  10. if(!in_array($IP, $ALLOWED_IP)) {
  11. foreach ($ALLOWED_IP as $val){
  12. if(strpos($val,'*')!==false){//Found * substitution symbol
  13. $arr=array();/ /
  14. $arr=explode('.', $val);
  15. $bl=true;//Used to record whether there is a successful match in loop detection
  16. for($i=0;$i<4;$i++) {
  17. if($arr[$i]!='*'){//If it is not equal to *, it will be checked. If it is a * symbol replacement, it will not be checked
  18. if($arr[$i]!=$check_ip_arr[ $i]){
  19. $bl=false;
  20. break;//Stop checking this ip and continue checking the next ip
  21. }
  22. }
  23. }//end for
  24. if($bl){//If it is true, find it If there is a successful match, return
  25. return;
  26. die;
  27. }
  28. }
  29. }//end foreach
  30. header('HTTP/1.1 403 Forbidden');
  31. echo "Access forbidden";
  32. die;
  33. }
  34. } < ;/p>
  35. /**

  36. * Obtain accessed IP
  37. * Enter description here...
  38. */
  39. function getIP() {
  40. return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"]
  41. :(isset($_SERVER ["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"]
  42. :$_SERVER["REMOTE_ADDR"]);
  43. }

Copy code

Call method: In the required files, add the call check_ip(); to achieve the purpose of IP access restriction; This function allows only the specified IP to access the file, and provides the wildcard character * in the IP to match multiple IPs.



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