Home>Article>Backend Development> Detailed explanation of how to restrict access to IP whitelist in PHP

Detailed explanation of how to restrict access to IP whitelist in PHP

藏色散人
藏色散人 forward
2020-01-22 11:02:09 3403browse

Detailed explanation of how to restrict access to IP whitelist in PHP

How does PHP restrict access to the IP whitelist?

1. Upload the code

config.php

//ip白名单配置 'ipWlist'=>[ 'ifFilter'=>true, //是否开启白名单功能 'wlist'=>[ '10.0.0.19', ], 'warea1'=>'10.8.0.0/16', //白名单网段1 'warea2'=>'10.12.0.0/16', //白名单网段1 ],

commonfunc.php

private function checkIp(){ $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"]; $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"]; $ipC=config('appconf.ipWlist'); if(!$ipC['ifFilter']){ return true; } if(in_array($user_IP, $ipC['wlist'])){ return true; } if( ! $this->ip_in_network($user_IP, $ipC['warea1'])){ if( ! $this->ip_in_network($user_IP, $ipC['warea2'])){ return false; } } return true; } private function ip_in_network($ip, $network) { $ip = (double) (sprintf("%u", ip2long($ip))); $s = explode('/', $network); $network_start = (double) (sprintf("%u", ip2long($s[0]))); $network_len = pow(2, 32 - $s[1]); $network_end = $network_start + $network_len - 1; if ($ip >= $network_start && $ip <= $network_end) { return true; } return false; }

2. Description

2.1 How to obtain IP

● $_SERVER["HTTP_VIA"] When there is a proxy server, it indicates the proxy server IP;

● $_SERVER["HTTP_X_FORWARDED_FOR"] obtains the client's real IP address through the proxy server;

● $_SERVER["REMOTE_ADDR"] The IP address of the user who is browsing the current page

Generally speaking, developers have a good understanding of the internal server architecture and can simply use REMOTE_ADDR, because REMOTE_ADDR cannot be forged and is more secure. The other two fields are not So reliable.

2.2 Some children's shoes do not use array config but define

It can be solved by json_encode, serialization, eval(), etc., as follows

define("IPFILTER",1); define('IPWLISTJSON',json_encode(['127.0.0.1',])); // 业务中 $wlist = json_decode(IPWLISTJSON,1); define('IPWLIST',"return ['127.0.0.1',];"); // 业务中 $wlist=eval(IPWLIST) define('IPWLIST',serialize(['127.0.0.1',])); // 业务中 $wlist=unserialize(IPWLIST);

You can also use the explode form of string special separator, etc., but I won’t give examples one by one here.

For more related php knowledge, please visitphp tutorial!

The above is the detailed content of Detailed explanation of how to restrict access to IP whitelist in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete