Block access to website from IP or region - php

I am trying to block the website to be viewed as not exist from certain region. Is this possible?
I know we can just put a die() and a blank page will be shown, but is there a way to make it seen like this domain does not exist?

You can use the geoip mod for apache ( http://www.maxmind.com/app/mod_geoip ). Mod_rewrite rules can then determine how to handle the page.
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA$
RewriteRule ^(.*)$ http://www.america.com$1 [F]
The F forbids page access

No, unless you have the DNS server for that domain under your control. Which you usually don't for domains like domain.tld, you can only adjust the content based on the clients ip - for example you can just serve an empty page as you suggested. But it is still possible to query the domain with tools like nslookup.

If you don't have access to the DNS server, you can add .htaccess rule to ban people from specific ipaddresses. Following are some sample .htaccess rules
order allow,deny
deny from 123.456.789.012 #block the visitors from the specific ipaddress 123.456.789.012
deny from 123.456.789. #blocks the visitors from all ip within the range 123.456.789.xxx (i.e. 123.456.789.000 – 123.456.789.255)
deny from 123.456. #blocks the visitors from all ip within the range 123.456.xxx.xxx
deny from 123. #blocks the visitors from all ip within the range 123.xxx.xxx.xxx
allow from all #allow from all other.

<?php
if (getenv(HTTP_X_FORWARDED_FOR)) {
$pipaddress = getenv(HTTP_X_FORWARDED_FOR);
$ipaddress = getenv(REMOTE_ADDR);
echo "Your Proxy IPaddress is : ".$pipaddress. "(via $ipaddress)" ;
} else {
$ipaddress = getenv(REMOTE_ADDR);
echo "Your IP address is : $ipaddress";
}
?>
This code u can use to get ip address of visitor...
To detect region you'll need some free api..Try this..
This Api can also be used..
The second one is really easy to use..
<A HREF="http://www.hostip.info">
<IMG SRC="http://api.hostip.info/flag.php?ip=12.215.42.19" ALT="IP Address Lookup">
</A>

Related

IP Check Via List

I have an ip list file for my country, as like this (txt document):
45.123.116.0/22
5.2.80.0/21
5.11.128.0/17
5.23.120.0/21
5.24.0.0/14
etc
i have two question about that.
1- can i forward the user, if he is in that list via .htaccess file? (if he is, use this adress.. if not this adress)
2- how can i check 'if the user is in my country' via PHP? i mean, how can i say something like that..
if (strstr('list.txt',$_SERVER['REMOTE_ADDR']))
*1).htaccess file
The visitor blocking facilities offered by the Apache Web Server enable us to deny access to specific visitors, or allow access to specific visitors. This is extremely useful for blocking unwanted visitors, or to only allow the web site owner access to certain sections of the web site, such as an administration*
ErrorDocument 403 /specific_page.html
area.*
order allow,deny
deny from 255.0.0.0
deny from 123.45.6.
allow from all
When using the "Order Allow,Deny" directive the requests must match either Allow or Deny, if neither is met, the request is denied.
doc 1)http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
doc 2)http://www.htaccess-guide.com/deny-visitors-by-ip-address/
2) Proof of Concept (can't say this works as is....)
$current_ip = $_SERVER['REMOTE_ADDR'];
$valid_ip = false;
// Convert IPs to Regex
foreach($cfg['ipallowed'] as $index=>$ip);
{
$ip = str_replace('.', '\\.', $ip);
$ip = str_replace('*', '[0-9]|^1?\\d\\d$|2[0-4]\\d|25[0-5]');
if (preg_match($ip, $current_ip)
{
$valid_up = true;
break;
}
}
if ($valid_ip)
1; you can redirect by IP to a holding page:
# Redirect a user to /specific_page.html based on their IP address.
RewriteCond %{REMOTE_ADDR} ^10\.0\.0\.2$ [OR]
RewriteCond %{REMOTE_ADDR} ^127\.0\.0\.2$
RewriteCond %{REQUEST_URI} !specific_page\.html$
RewriteCond %{REQUEST_URI} !\.(js|png|gif|jpg|css)$
RewriteRule ^ /specific_page.html [R=302,L]
2; see this question/answer which recommends using http://www.hostip.info/use.html.

What's the best way to restrict IP address?

Suppose I wanted to ban a specific IP address from accessing the whole domain name (+ all included subdomains). At first I began with the following snippet to add the following lines to the .htaccess file:
$info = 'Order Deny,Allow
Deny from' . IPtoBlock();
if (getIP()){
$htaccess = fopen('.htaccess', 'r+');
fwrite($htaccess, $info);
fclose($htaccess);
}
But is it more relevant to redirect the user to something else? After all, he is still capable of making a request towards the server despite the immediate redirect.
$deny = array('192.168.1.0', '192.168.1.1', '192.168.1.2');
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
header("location: http://www.google.com/");
}
or simply kill the page?
$deny = array('192.168.1.0', '192.168.1.1', '192.168.1.2');
if (in_array ($_SERVER['REMOTE_ADDR'], $deny)) {
die('Access restricted');
}
What is the best approach towards this issue?
In jour .htaccess :
Order Allow,Deny
Allow from all
Deny from 123.123.123.123
User with ip 123.123.123.123 will have a 403.
And if you want to redirect to a specific page, add :
ErrorDocument 403 /forbidden.php
Edit : For ban Ip from text file in htaccess, take a look here : Ban IPs from text file using htaccess
In your .htacces File:
Order Deny,Allow
Deny from all
Allow from xx.xx // This will be your local IP address
Allow from yy.yy.yy.yy // Your server IP address
Except from these scenario, no one can access your website.
The best ist do block this attempt before it even reaches your webserver. That means blocking on a level like iptables (firewall; or if you can't do that and are using a load balancer, then block it there).

How to redirect everyone but me on Development Subdomain with .htaccess or PHP

I have a development subdomain which is http://dev.example.com, how can I stop this website being indexed in search engines and if someone types in that link, how do I redirect them to the main site?
I tried doing it with .htaccess but when I added this line of code it showed that page on the index.html file and messed up the page:
RewriteRule .? http://www.google.com [L]
Any help is appreciated, thank you.
$your_ip = '';
if($_SERVER['REMOTE_ADDR' != $your_ip){
header("location:".$your_redirect_url);
exit;
}
You just need this code in your .htaccess:
Order Deny,Allow
Deny from all
Allow from aa.bb.cc.dd
Allow from mm.nn.pp.qq
Replace aa.bb.cc.dd, mm.nn.pp.qq etc with your own IP address. This will not only block all search bots it will block all unwanted visitors to your dev site.

How do I allow only certain IP's to view webpages?

I'm trying to get a PHP script to work where it compares the IP of the person against a text file(one IP per line). If the person's IP is not in the text file, then he gets redirected to declined.html. I know I could use .htaccess for this but the IP list could get really, really long.
This is the code that I have so far:
<?php
$ipArray = file('ip.txt');
unset($allowed);
foreach ($ipArray as $ipTest) if (substr_count($_SERVER['REMOTE_ADDR'],trim($ipTest)) != "0") $allowed = true;
if ($allowed != true) {
header('location: /declined.html'); // the banned display page
die();
}
?>
I want to be able to call this script in every page that I only want certain IP's to see, this is what I'm trying to call it with:
<? include('ip_allow.php'); ?>
When I call the PHP script in the HTML page when my IP is NOT in ip.txt, it does not redirect me to /declined.html! How can I fix this? Again, my question is not how to use .htaccess, but how to fix my script! Thanks.
For IP filtering, it's best to do it as early as possible in the processing chain. In order of preference:
router
firewall
webserver
script
Most likely you don't have access to the router or firewall levels, but you CAN use Apache's mod_rewrite to have a dynamic block using an external file. Set up your "enabled IPs" file as follows:
a.b.c.d ALLOWED
b.c.d.e ALLOWED
c.d.e.f ALLOWED
etc...
It's basically "key value", where the key is the IP address
Then your mod_rewrite rules (I've numbered them for reference)
1. RerwriteMap ipfiltermap txt:/path/to/your/ips/list
2. RewriteCond %{REMOTE_ADDR} (.*)
3. RewriteCond %{ipfiltermap:%1} !ALLOWED
4. RewriteCond %{REQUEST_URI} !^/declined.html
5. RewriteRule .* /forbidden.html [L]
They work as follows:
Defines the allowed IPs as a "key value" pair, where the keys are the allowed IPs, and the value is the word "ALLOWED", as a mapping named "ipfiltermap"
Captures the remote address of the current request (the client IP)
Using the IP captured in step 2, look it up in the ipfiltermap, and see if the the IP does NOT have the word 'ALLOWED'
Specifically exempt your 'declined' page from the IP enforcement - if this wasn't here, disabllowed IPs would enter an infinite redirect loop
If all 3 of the RewriteConds match, then the user is from a forbidden IP, and should be redirected to the fobidden page.
Relevant Apache docs for all this are here.
If you place your configuration in your Apache configuration directly, it won't incur the speed penalties of .htaccess lookups -- but that would mean you'd need to reload the Apache configuration whenever the list is modified. (Though Marc's answer avoids this very nicely.)
The mod_authz_host.c is optimized for moderately fast searching. If you're reading a text file in your script every execution, you're already several times slower than Apache. Apache reads the configuration once, converts the IP addresses to a binary format once, and can then use very fast integer arithmetic to determine if hosts are allowed or not.
Furthermore, it's already debugged and working. It'd take you less time to deploy it than it would to find the bug in your current code -- and even then, your current code would -- on every access-controlled request -- re-read (and re-parse into an array) the textual description of IP addresses, convert the IP address from the remote peer into a text version, and then perform a very slow text-based comparison over the entire array.
If speed is of real importance, then you should investigate doing the access control via your system firewall. iptables has optimized routines to find matching IP addresses among a list of allowed or denied hosts and won't waste any time performing any protocol analysis. Of course, this is a much heavier all-or-nothing approach that would require an annoying separation of content among listening ports if some content is available for all.
I would guess you have files in the wrong directory, or PHP not working or some other more basic configuration issue, since I tested your code and it works fine for me.
The file() command includes the \n character at the end of each line, so each line is actually something like 0.0.0.0\n which is returning false every time.
Use this:
$ipArray = file('ip.txt', FILE_IGNORE_NEW_LINES); // Try specifying an ABSOLUTE path to this file.
$allowed = false; // Rather than unset($allowed), this will prevent notice errors too!
foreach ($ipArray as $ipTest) if ($_SERVER['REMOTE_ADDR'] == $ipTest) $allowed = true;
Also just to point out in your header line, Location should start with a capital letter and you should specify a full URI to the file:
header('Location: http://example.com/declined.html');

How to access a website only from a specified IP using PHP

I need to access a site only from a specific IP address.
Is that possible using PHP.
The project is under development and some people used that and say "The site is not good". So
i like to avoid that kind of things. That's why i need this solutin.
try this:
if ($_SERVER['REMOTE_ADDR'] == "x.x.x.x")
echo "admin";
else
echo "user";
it checks the ip of user and do the action.
I would suggest to use a .htaccess file instead of adding this to your php-code:
RewriteEngine On
RewriteBase /
# IPs that are still allowed to view everything
RewriteCond %{REMOTE_ADDR} !^213.123.39.12$ [NC]
RewriteRule !^(noentry_image.jpg|favicon.ico)$ sorry_stay_out.html [L]
just put the ".htaccess" file into your root-dir of your website. Then everybody will be redirected to the sorry_stay_out.html page, that contains the noentry_image.jpg.
All visitors from the IP that is allowed will see the site as normal. You can repeat the line "RewriteCond %{REMOTE_ADDR} !^213.123.39.12$ [NC]" with different IPs as often as you want, to add additional IPs.
Alternative with just blocking:
order allow,deny
allow from 62.57.16.192
allow from 72.232.56.154
deny from all
You can use $_SERVER variables to check if the source is from the IP you're limiting to. Here are some useful function snippets ($s is just $_SERVER):
function gethostname($ip){
return gethostbyaddr($ip);}
function gethostnamepretty($ip){
$host=gethostbyaddr($ip);
$host=explode('.',$host);
$max=count($host);
return $host[$max - 2];}
function getRawRealIP($s){
if (!empty($s['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip=$s['HTTP_CLIENT_IP'];
}
elseif (!empty($s['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip=$s['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$s['REMOTE_ADDR'];
}
return $ip;}
function checkIP($ip){
return long2ip(ip2long($ip));}
function useragent($s){
return $s['HTTP_USER_AGENT'];}

Categories