note 86793 deleted from function.ip2long by cmb
| From: | cmb@php.net | Date: | Sun, 18 Aug 2019 08:44:10 +0000 |
| Subject: | note 86793 deleted from function.ip2long by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-211943@lists.php.net to get a copy of this message | ||
Note Submitter: kaputt at starnet dot md
----
Hi all!
I've maded simple script that allow you filter traffic by networks, like if you want to deny
192.168.0.0/24
I used ncritten's myip2long function for this.
Sorry for such non-optimized code, but it works enough good =)
file iplist.txt:
192.168.0.0/24
172.16.0.0/16
10.0.0.0/8
<?php
########### ncritten's function myip2long
function myip2long($ip) {
if (is_numeric($ip)) {
return sprintf("%u", floatval($ip));
} else {
return sprintf("%u", floatval(ip2long($ip)));
}
}
########### function to chek ip if it in one of denyied/allowed networks =)
function ipfilter($ip) {
$match = 0;
### converting ip address in binary
$ip_addr = decbin(myip2long($ip));
### the file wich contains allowed/denyied networks
if (fopen("iplist.txt", "r")) {
$source = file("iplist.txt");
foreach ($source as $line) {
### exploding each network to obtaid network address and cidr
$network = explode("/", $line);
$net_addr = decbin(myip2long($network[0]));
$cidr = $network[1];
### and finaly cheking quantity of network bits from left to right wich is equal to cidr is equal to
the same bits of ip address
if (substr($net_addr, 0, $cidr) == substr($ip_addr, 0, $cidr)) {
$match = 1;
break;
}
}
}
return $match;
}
### this function will return 1 if IP match to some network or 0 if will not match
### and finaly the chek will be like this
$user_ip = $_SERVER['REMOTE_ADDR'];
if (ipfilter($user_ip) == 1) echo "allowed!";
else echo "deny!";
?>
Good Luck!
P.S. Sorry for my bad english =)