Last active
February 19, 2022 22:25
-
-
Save jxmot/76891f9ba76fb42a4862e9dc2fcb2c4b to your computer and use it in GitHub Desktop.
IP Address Validator - PHP & JSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
ip_isvalid() - Checks an IP address against a list of | |
valid IP addresses. | |
Params: | |
$_ip - can be `null` or an IP address. If `null` | |
then `REMADDR` will be checked. | |
Returns: An object, where `r` is either `true` (the | |
IP was found) or `false`. And `n` will contain | |
the associated name found in the `ipvalid.json` | |
file. | |
NOTE: This is only a simple security method, it | |
should not be used where security is crucial. | |
And it may not be suitable for use with a high | |
volume of IP traffic. | |
USAGE: | |
// this would typically be one of the first | |
// things executed in a PHP end point. | |
require_once './ip_isvalid.php'; | |
$ret = ip_isvalid(); | |
if($ret->r === false) { | |
header('HTTP/1.0 403 Not Allowed'); | |
exit; | |
} else { | |
echo $ret->n . " is here!\n\n"; | |
// valid IP, continue.... | |
} | |
*/ | |
define('REMADDR', ((isset($_SERVER['REMOTE_ADDR']) === true) ? $_SERVER['REMOTE_ADDR'] : 'none')); | |
$valid = json_decode(file_get_contents('./ipvalid.json')); | |
function ip_isvalid($_ip = null) { | |
global $valid; | |
$ip = ''; | |
$ret = new stdClass(); | |
$ret->r = false; | |
$ret->n = ''; | |
if(($ip = ($_ip === null ? REMADDR : $_ip)) !== 'none') { | |
foreach($valid->list as $vip) { | |
if($ip === $vip[0]) { | |
$ret->r = true; | |
$ret->n = $vip[1]; | |
break; | |
} | |
} | |
} | |
return $ret; | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"_comment":"Add entries to list[] as needed. Keep the total quantity within reason!", | |
"list": [ | |
["0.0.0.0","example"], | |
["a.b.c.d","this is the identifying name for the ip owner"] | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment