How to block IP within PHP

Posted by Nurasto | July 11, 2011 | Software and Web Development | 1 Comments

In one project I was requested by client to block IPs to web based application, he just want hardcode implementation and gives me the ips. There’s multiple solution to achieve this task.

Array

<?php

$blocked_ip = array('192.168.2.100', '192.168.2.105');
$visitor_ip = $_SERVER['REMOTE_ADDR'];

if(array_search($visitor_ip, $blocked_ip) === FALSE)
{
    header('Location: denied.php');
    exit();
}

//your code for allowed ip

?>

Let me explain what happen to those code:

  1. Specify blocked IP
  2. Get current visitor IP from web server variable, in this case i was using Apache
  3. If IP is match then redirect visitor to denied.php

Database Driven

Execute following table to your database

CREATE TABLE blocked_ip (
  `id` INT UNSIGNED AUTO_INCREMENT,
  `ip` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO blocked_ip (ip) VALUES
('192.168.2.101'),
('192.168.2.102');

Then use that table for the following example

<?php
//define your database environment
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'mytable';
//get remote ip
$visitor_ip = $_SERVER['REMOTE_ADDR'];
$mysql_link = mysql_connect($dbhost, $dbuser, $dbpass) or die('Can not connect to database server');
$mysql_database = mysql_select_db($dbname) or die('Can not use database');
$mysql_query = mysql_query("SELECT COUNT(ip) AS total_rows FROM blocked_ip WHERE ip = '{$visitor_ip}'") or die('Can not execute query');

$result = mysql_fetch_array($mysql_query);

if($result['total_rows'] > 0)
{
	header('location: denied.php');
	exit();
}

//your code for allowable ip

?>

Those code are easy to understand for beginner, has same meaning with first example but we use database query to look at blocked_ip table.

The real world problem you need to solve are:

  1. Multiple IP, sometimes you will get such condition. You may use explode, implode, or foreach
  2. Proxy, you need to consider visitor whom use proxy to access your web apps
Many thing you could implement from this piece of code. Fell free to improve it.

Comments

  1. Nancy says:

    Thanks for the share!
    Nancy.R

Sorry, comments are closed

Bit and Bytes

Hello. My name is Dityo Nurasto. I am working as freelance software and web developer.

This is my personal playground. Enjoy your stay and don't hesitate to send comments.

ShoutBox