Home > Software engineering >  How to load a list of ip ranges to use it with $allowedIps script?
How to load a list of ip ranges to use it with $allowedIps script?

Time:10-23

Sorry I'm a newbie, but I'm trying to use the script I found here:

Only allow users on page if IP address is approved

    $allowedIps = ['x.x.x.x', 'x.x.x.x'];
$userIp = $_SERVER['REMOTE_ADDR'];

if (!in_array($userIp, $allowedIps)) {
    exit('Unauthorized');
}

But instead, I want to load thousands of ip ranges from a .txt file

like this: (I don't know correct function)

 $allowedIps = ['www.example.com/ip_list.txt'];

ip_list.txt list:

xx.xxx.xxx.xx/30 
xx.xxx.xxx.xx/78 
xx.xxx.xxx.xx/59 

CodePudding user response:

/*
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');
}

PHP manual for file_get_contents

CodePudding user response:

This script will get the IP list from the file, split it into lines, then convert the CIDR notation to an array of IPs, and will merge them all together. Then a check is performed and a HTTP 403 code is given if the remote address is not in the list of acceptable IPs.

<?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;
}
  • Related