I am building an admin panel. and I want to block certain IP ranges. I’m testing this on my localhost wamp server but ir doesn’t seem to redirect me.
<?php if($_SERVER['REMOTE_ADDR'] == '127.0.0..*') header("Location: http://google.com"); else echo "Hai"; ?>
Any input is appreciated.
Advertisement
Answer
Is sufficient to use string comparison
if (strncmp('127.0.0.', $_SERVER['REMOTE_ADDR'], 8) === 0) header("Location: http://google.com"); else echo "Hai";
Update: Taken from the comments of inits answer
Suppose i want to block any IP coming from this range: 192.168.0.1-255. What would be the best solution for it ? Thanks.
Then just make the same string comparison against this block
if (strncmp('192.168.0.', $_SERVER['REMOTE_ADDR'], 10) === 0) header("Location: http://google.com"); else echo "Hai";
If you want to test the remote address against both blocks at once, you will probably put them together into one expression. This time we need a different approach
if (in_array(substr($_SERVER['REMOTE_ADDR'], 0, strrpos($_SERVER['REMOTE_ADDR'], '.')), array('127.0.0', '192.168.0'))) { header("Location: http://google.com"); else echo "Hai";
The substr()
-part takes the IP until the last .
. We can just try to find this string in a set (-> array) of IP-prefixes.