对不起,我是一个新手,但我正试图使用我在这里找到的脚本:
仅允许用户在IP地址被批准的情况下进入页面
$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');
}
file_get_contents PHP手册
该脚本将从文件中获取IP列表,将其分成几行,然后将CIDR符号转换为IP数组,并将它们合并在一起。如果远程地址不在可接受的ip列表中,则执行检查并给出HTTP 403代码。
<?php
// Function courtesy of the following answer
// https://stackoverflow.com/questions/4931721/getting-list-ips-from-cidr-notation-in-php
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;
}