Link to home
Start Free TrialLog in
Avatar of Souled
SouledFlag for Kuwait

asked on

Redirect certain IP's

Hi all,

I need to redirect a certain IP's to a specific login page.
for example:
IP: 62.150.X.X
redirected to login.php

The reason I need this code is that I would like to redirect a certain country to a login page on my chat site, other countries have direct access to the chat service without providing username/password.

One more thing, I have around 10 IP's to redirect.


Avatar of Roonaan
Roonaan
Flag of Netherlands image

Try the snippet below:

<?php
/* put this at the top of your page */
$certain_ips = array('62.150.0.1','62.150.0.2');
if(in_array($_SERVER['REMOTE_ADDR'], $certain_ips))
{
header('Location:login.php');
exit();
}
?>

Regards

-r-
Avatar of Souled

ASKER


I have tried it and it worked fine.

one thing has to be changed though. The form which the IPs r entered here is static.
What i meant 62.150.X.X is that we need to use only 62.150 and any other possible class following without entering them manually.

I have tried to change this line to the following form

$certain_ips = array('62.150','213.189');

but it did not work.

any solution for that?

Well, you could use:

foreach($certain_ips as $ip)
{
 if(substr($_SERVER['REMOTE_ADDR'], 0, strlen($ip)) == $ip)
 {
  header('Location:login.php');
  exit();
 }
}

An alternative would be a preg match, but the solution above is somewhat more maintainable in my opinion.

-r-
Avatar of Souled

ASKER

How can I specify the banned IPs in the last code?

ASKER CERTIFIED SOLUTION
Avatar of Roonaan
Roonaan
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Diablo84
Diablo84

A regex example derived from an IP blocking script I had in action on a site i built some time back:

$ip[] = '^([6][2](\.[1][5][0])(\.[0-9]{1,3}){2})$';

//some other examples of use, you can remove this block of code if you don't need it for reference
//$ip[] = '111.111.111.111';
//$ip[] = '^([1][1][1](\.[0-9]{1,3}){3})$';  //BAN 111.*
//$ip[] = '^([1][1][1](\.[1][1][1])(\.[0-9]{1,3}){2})$';  //BAN111.111.*
//$ip[] = '^([1][1][1](\.[1][1][1])(\.[1][1][1])(\.[0-9]{1,3}))$';  //BAN 111.111.111.*
//$ip[] = '^([0-9]{1,3}(\.[0-9]{1,3}){3})$';  //to ban ALL

$user_ip = $_SERVER['REMOTE_ADDR'];

foreach($ip as $var) {
 if(ereg($var,$user_ip)){
  header("location: login.php");
  exit;
 }
}
Avatar of Souled

ASKER



it worked just fine THANKS ALOT MAN


u earned it :)


Avatar of Souled

ASKER

Roonaan

I know had accepted the code already
but I have a small problem with it now

I have a list of 10 banned IPs. The code provided by you bans only the first two in the array.

Could you fix that? I can put this question as new ticket if you wish