IP Banning with PHP
-
By: Jacob Manser (lefteh)
Blocking certain IP addresses from your site is actually much easier than you might think.
In fact, it is only a seven-line code inserted at the top of your page!
The code:
1 : < ?php
2 : $banned = array("24.91.102.173", "64.21.162.113");
3 : if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
4 : echo "You have been banned.";
5 : exit;
6 : }
7 : ?>Please note that the used IP addresses are randomly selected numbers.
Now, for the explanation of the code.
- Line 1 simply opens the PHP code.
- Line 2 sets the variable $banned to an array containing all the IP addresses you want to be blocked from your site.
- Line 3 opens a conditional. The conditional uses the in_array() function. This function checks if the first argument is in the second argument, which is an array. Our first argument, $_SERVER['REMOTE_ADDR'], is automatically set to the viewer’s IP address.
- Line 4 echoes the message “You have been banned” if the user’s IP address is in the array $banned.
- Line 5 exits the page, not executing any code below line 5 if the above conditions are met.
- Line 6 ends the conditional.
- Line 7 ends the PHP code.
So, if you are implementing this code into your page, just put it above the HTML tag like below:
< ?php
$banned = array("24.93.100.113");
if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
echo "You have been banned.";
exit;
}
?>And that is the simple code that blocks chosen IP addresses from your site.If you need any further assistance, you can contact me:
iChat: bushisah8er
Email: lefteh@gmail.comPublished via PHPmac - IP Banning through a Creative Commons License
























March 8th, 2006 at 10:08 am
you can shorten
if (in_array($_SERVER['REMOTE_ADDR'], $banned)) {
echo “You have been banned.”;
exit;
}
to
if (in_array($_SERVER['REMOTE_ADDR'], $banned))
die(”suck it”);
March 12th, 2006 at 8:36 am
Indeed you can.
However, I wanted to keep the tutorial short and to fall in line with my others. I hadn’t explained shortening conditionals yet, and so used a full conditional.