Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
How to load a list of ip ranges to use it with $allowedIps script?

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 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

/*
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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!