My digital scrapbook

How to block IP within PHP

on under Software and Web DevelopmentOne Comment

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.



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

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

//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 (
  `ip` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`)

INSERT INTO blocked_ip (ip) VALUES

Then use that table for the following example

//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');

//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.