Home Forum Search Contact Us Advertise
Tutorial

IP Banning

Thumbnail

by Darkman | in PHP | posted April 20, 2007

Default starDefault starDefault starDefault starDefault star (0 votes) | 4273 views

Learn how to ban a single IP or multiple IP addresses from accessing your website.

Add to del.icio.us | Digg! Digg this | Dot This

You must login in order to rate this.
In this tutorial, we will see how we can ban specific IPs from accessing a webpage. We will see the code part by part now.

PHP:


<?php 
// The ip addresses to be banned separated by |
$ban "34.43.97.31|86.53.73.27|41.107.14.621";
?>


We are storing the various IPs to be banned in a variable separated by pipe symbol '|'.
We will later split them using the |.

PHP:


<?php 
// Store current user's IP in a variable
$visitor $_SERVER['REMOTE_ADDR'];
?>


This line fetches the IP address of the current user who visits your site. We store it in a variable for convenience.

PHP:


<?php 
// Split the IPs using |
$list explode("|"$ban);
?>


The explode() function splits the string $ban by the Pipe symbol and store the various values in an array.

PHP:


<?php 
foreach($list as $ip)
{
  if(
$visitor_ip == $ip)
  {
    echo 
"You are banned from this site";
    exit;
  }
}
?>


An usual foreach() loop to fetch the various elements in the array. The if statement check if the current user's IP is the same as any of the one specified. If so a message is displayed to the user. The exit; statement makes sure that the rest of the codes are not executed.

The Total code should look like this :

PHP:


<?php 

// The ip addresses to be banned separated by |
$ban "34.43.97.31|86.53.73.27|41.107.14.621";

// Store current user's IP in a variable
$visitor $_SERVER['REMOTE_ADDR'];

// Split the IPs using |
$list explode("|"$ban);

foreach(
$list as $ip)
{
  if(
$visitor_ip == $ip)
  {
    echo 
"You are banned from this site";
    exit;
  }
}

?>



You can save this file as ip_check.php and use it to protect other pages by including this file on the top of every page as :

PHP:


<?php 
include ('path/ip_check.php');
?>



Hope you found this tutorial Helpful.


Note : The IP addresses used in this tutorial were just some random ones. They were not intentional.

 

There are 2 comments to this post.