如何加载 ip 范围列表以将其与 $allowedIps 脚本一起使用?
How to load a list of ip ranges to use it with $allowedIps script?
抱歉,我是新手,但我正在尝试使用我在此处找到的脚本:
$allowedIps = ['x.x.x.x', 'x.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
但是,我想从 .txt 文件加载数千个 IP 范围
像这样:(我不知道正确的函数)
$allowedIps = ['www.example.com/ip_list.txt'];
ip_list.txt 列表:
xx.xxx.xxx.xx/30
xx.xxx.xxx.xx/78
xx.xxx.xxx.xx/59
/*
You need the proper fopen wrapper server settings for reading
URLs using file_get_contents, see the notes at the PHP manual
*/
$allowedIps = explode('\n', file_get_contents('http://my/url/file.txt'));
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
此脚本将从文件中获取 IP 列表,将其拆分成行,然后将 CIDR 表示法转换为 IP 数组,并将它们全部合并在一起。然后执行检查,如果远程地址不在可接受的 IP 列表中,则会给出 HTTP 403 代码。
<?php
// Function courtesy of the following answer
//
function cidrToRange($cidr) {
$range = array();
$cidr = explode('/', $cidr);
$range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
$range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
return $range;
}
$file = 'http://www.example.com/ip_list.txt'; // don't forget http://
$lines = file($file);
$ips = [];
foreach ($lines as $line) {
$ips = array_merge($ips, cidrToRange($line));
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (!in_array($user_ip, $ips)) {
header('HTTP/1.0 403 Forbidden');
exit;
}
抱歉,我是新手,但我正在尝试使用我在此处找到的脚本:
$allowedIps = ['x.x.x.x', 'x.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
但是,我想从 .txt 文件加载数千个 IP 范围
像这样:(我不知道正确的函数)
$allowedIps = ['www.example.com/ip_list.txt'];
ip_list.txt 列表:
xx.xxx.xxx.xx/30
xx.xxx.xxx.xx/78
xx.xxx.xxx.xx/59
/*
You need the proper fopen wrapper server settings for reading
URLs using file_get_contents, see the notes at the PHP manual
*/
$allowedIps = explode('\n', file_get_contents('http://my/url/file.txt'));
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $allowedIps)) {
exit('Unauthorized');
}
此脚本将从文件中获取 IP 列表,将其拆分成行,然后将 CIDR 表示法转换为 IP 数组,并将它们全部合并在一起。然后执行检查,如果远程地址不在可接受的 IP 列表中,则会给出 HTTP 403 代码。
<?php
// Function courtesy of the following answer
//
function cidrToRange($cidr) {
$range = array();
$cidr = explode('/', $cidr);
$range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
$range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
return $range;
}
$file = 'http://www.example.com/ip_list.txt'; // don't forget http://
$lines = file($file);
$ips = [];
foreach ($lines as $line) {
$ips = array_merge($ips, cidrToRange($line));
}
$user_ip = $_SERVER['REMOTE_ADDR'];
if (!in_array($user_ip, $ips)) {
header('HTTP/1.0 403 Forbidden');
exit;
}