I need to change currency based on user location. This is my code
<?php
$ipaddress = $_SERVER['REMOTE_ADDR'];
$location = unserialize( file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $_SERVER['REMOTE_ADDR']) );
if($location["geoplugin_countryCode"] === "US")
{
// block to set us currency
}
else{
// user can choose their own currency from array (excluding us)
}
?>
I uploaded it on a server, and to check if the functionality works correctly or not and I used different vpn chrome extension. The problem is all the time else part is alone gets executed even when I choose us as vpn server. I don't know What is causing this problem.
Most probably the issue is that you use $_SERVER['REMOTE_ADDR'].
If you are using a proxy, you should use $_SERVER['HTTP_X_FORWARDED_FOR']
Related
The IP address of the computer that I am using is the one specified in $ip. The problem is that when $userip != $ip, the message is displayed, which it should not. The first version of the if statement is ideally how I want the page to work. Any ideas/suggestions? Thanks in advance.
Note: The purpose of the if statement is to ensure that the users access the site from a particular computer. For example, employees can only access the site from their work station computer (not from PCs). If they are not at their work station computer, then the message is displayed.
Note: I got the $ip from running an "ipconfig /a"ll command.
Note: I am currently testing this with one IP address and I will eventually test with multiple ones.
$userip = ($_SERVER['REMOTE_ADDR']);
$ip = '172.34.56.202';
if ($userip != $ip) {
echo "<h3>" . "ACCESS DENIED. Your IP address is not in the list of allowed IPs" . "</h3>";
} else{
$URL="http://www.yahoo.com";
header ("Location: $URL");
}
?>
I also tried to change around the operations of the if statement in this version, but it still doesn't work..the error message is still displayed instead of directing the user to a different page:
<?php
error_reporting(E_ALL);
$userip = ($_SERVER['REMOTE_ADDR']);
$ip = '172.34.56.202';
if ($userip == $ip) {
$URL="http://wt-ws.delta.lasalle.edu/tempProject/timeSheetProject/TimeSheet.php";
header ("Location: $URL");
} else{
echo "<h3>" . "ACCESS DENIED. Your IP address is not in the list of allowed IPs" . "</h3>";
}
?>
I just tested the above code and it works just fine on my end for the page I created.
The only thing I would suggest is doing
echo($userip);
To see what the value is for $userip. As if you are doing this on a test box installed on your machine your IP very well could be 127.0.0.1 , as you are viewing the file local.
To your updated question
When you use ipconfig /a this gives you the IP address assigned to your machine. Most networks use a subnet mask and a private IP Address. For example if you use ipconfig /a and get an IP address in the following ranges it is a private non routable IP address.
10.0.0.0 - 10.255.255.255 - Class A
172.16.0.0 - 172.31.255.255 - Class B
192.168.0.0 - 192.168.255.255 - Class C
To find your public IP Address you can do this a couple of ways:
You can google what is my ip?
www.ipchicken.com
www.whatismyip.com
Maybe try using the identical comparison operators such as !== or === ?
Before PHP 5.4 when running retrieving the users IPAddress using $_SERVER['REMOTE_ADDR'] the result would be the users external IPV6 IPAddress.
EG: 60.123.456.168
However since updating my server to PHP 5.4 the returned users IPAddress seems to be their internal IP:
EG: 192.168.1.34
This becomes an issue if you want a specific office or 'router' to see a particular group of content or in our case debug code.
I tried using the other IP option $_SERVER['HTTP_X_FORWARDED_FOR'] but this isn't available on all servers.
Is their another way to grab the users external ipaddress in PHP >= 5.4 or has this functionality been removed?
this even checks for proxy servers and still reveal correct user ip
<?php
function get_real_ip()
{
if (isset($_SERVER["HTTP_CLIENT_IP"]))
{
return $_SERVER["HTTP_CLIENT_IP"];
}
elseif (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
{
return $_SERVER["HTTP_X_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_X_FORWARDED"]))
{
return $_SERVER["HTTP_X_FORWARDED"];
}
elseif (isset($_SERVER["HTTP_FORWARDED_FOR"]))
{
return $_SERVER["HTTP_FORWARDED_FOR"];
}
elseif (isset($_SERVER["HTTP_FORWARDED"]))
{
return $_SERVER["HTTP_FORWARDED"];
}
else
{
return $_SERVER["REMOTE_ADDR"];
}
}
$IP_Address = get_real_ip();
echo $IP_Address
?>
It is not PHP's fault. PHP doesn't detect anything but just reading environment variable.
You have some proxy probably, that is not properly configured.
Ok,
Figured out this issue appears to be due to our Newb server setup.
As the server was in fact running from a localhost and networked through Windows (I wasn't aware it was till now).
This explains why the Local IPAddress was coming up.
False alarm :)
Thanks everyone for your help though!
I wanna display user's/visitor's country flag on my site.
I am using different technologies like php,jsp and simple html. So I want a code which by placing on my site, visitors can see and it should run in all platform.
In short I want country detection API. If anybody can help me, I'll be very thankful.
Source :
http://www.shorter.in/#flag
<img src="http://shorter.in/flag.php">
Example for the code given above.
a busy cat http://shorter.in/flag.php
I guess this is what you are looking for.
My service, ipdata.co provides an IP Geolocation API on https://api.ipdata.co and serves flags on for example https://ipdata.co/flags/cu.png.
All you have to do is know your visitors' country's iso code and you can fill it in
ipdata.co/flags/country-code.png
You can of course get the user's country code by calling https://api.ipdata.co/user-ip.
Sample embed;
<img src="https://ipdata.co/flags/us.png" alt="US Flag">
Gives
Edit
We now also provide you with the country emoji flag and country emoji unicode.
Yeah there is something already available and you don't have to reinvent the wheel.
Check this thing out.
http://api.hostip.info/flag.php?ip=12.215.42.19
Grab your user's IP using PHP and pass it to the API.
<?php
$ip=$_SERVER['REMOTE_ADDR'];
?>
Putting it all together
<?php
$ip=$_SERVER['REMOTE_ADDR'];
echo "<img src='http://api.hostip.info/flag.php?ip=$ip' />";
?>
You can use the GeoIP extension and then map the country in question to a given icon.
$countryName = geoip_country_name_by_name($_SERVER['REMOTE_ADDR']);
echo $countryName;
Note that getting the country via IP is not exact.
Get the IP of visitor.
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
Use ip2location to find the country of the user.
http://dev.maxmind.com/geoip/legacy/geolite/
Compare the resulting country to a list of images and display the matching image.
I suggest using a database to store the country name and the path to the associated image.
I often hear people say to use "$_SERVER['SERVER_ADDR']", but that returns the LAN IP of my server (e.g. 192.168.1.100). I want the external IP.
There is NO way to get your underlying IP Address that has been designated by your ISP via conventional PHP if you are using a router. A way to get the external IP is to find a service that will obtain it for you and echo the address back to you. I found a handy service which does just that. http://ipecho.net/
You can use:
$realIP = file_get_contents("http://ipecho.net/plain");
Just query a host that returns your IP address:
$externalContent = file_get_contents('http://checkip.dyndns.com/');
preg_match('/Current IP Address: \[?([:.0-9a-fA-F]+)\]?/', $externalContent, $m);
$externalIp = $m[1];
or, set up a service that simply echoes just the IP, and use it like this:
$externalIp = file_get_contents('http://yourdomain.example/ip/');
Set up the service yourself by simply echoing the remote IP address, or pay someone to host it. Do not use somebody else's server without permission. Previously, this answer linked to a service of mine that's now being hit multiple times a second.
Note that in an IP network with one or more NATs, you may have multiple external IP addresses. This will give you just one of them.
Also, this solution of course depends on the remote host being available. However, since there is no widely implemented standard (no ISP and only some home routers implement UPnP), there is no other way to get your external IP address. Even if you could talk to your local NAT, you couldn't be sure that there isn't another NAT behind it.
I'm going to add a solution because the others weren't quite right for me because they:
need to be run on a server with a domain name e.g. gethostbyname() (if you think about it, you don't actually have the problem if you know this a priori)
can't be used on the CLI (rely on something in $_SERVER to be set by a web server)
assume a specific format of ifconfig output, which can include multiple non-public interfaces
depend on parsing someone's website (who may disappear, change the URL, change the format, start lying to you, etc, all without notice)
This is what I would suggest:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$res = socket_connect($sock, '8.8.8.8', 53);
// You might want error checking code here based on the value of $res
socket_getsockname($sock, $addr);
socket_shutdown($sock);
socket_close($sock);
echo $addr; // Ta-da! The IP address you're connecting from
The IP address there is a Google public DNS server. I trust they'll be around and running it for a while. It shouldn't really matter what address you use there as long as its a public IP address that belongs to someone who doesn't mind random connection attempts too much (yourself maybe?).
This is based on an answer I came across when I had a similar problem in Python.
P.S.: I'm not sure how well the above would work if there is sorcery going on between your machine and the internet.
You could parse it from a service like ip6.me:
<?php
// Pull contents from ip6.me
$file = file_get_contents('http://ip6.me/');
// Trim IP based on HTML formatting
$pos = strpos( $file, '+3' ) + 3;
$ip = substr( $file, $pos, strlen( $file ) );
// Trim IP based on HTML formatting
$pos = strpos( $ip, '</' );
$ip = substr( $ip, 0, $pos );
// Output the IP address of your box
echo "My IP address is $ip";
// Debug only -- all lines following can be removed
echo "\r\n<br/>\r\n<br/>Full results from ip6.me:\r\n<br/>";
echo $file;
You could try this:
$ip = gethostbyname('www.example.com');
echo $ip;
to get the IP address associated with your domain name.
I know this question is old and long answered, but I was googling for the same thing and want to add my own "hack". For this to work your webrequest has to come from an external IP address or you have to alter $own_url to a url that does an external request to itself.
The point is, if you let the script do a request to itself than you get it's external IP address.
<?php
if (isset($_GET['ip'])) {
die($_SERVER['REMOTE_ADDR']);
}
$own_url = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$ExternalIP = file_get_contents($own_url.'?ip=1');
echo $ExternalIP;
?>
I think there is much code for this things in others answers, but my answer is short, but you need to execute a command in shell to get the ip...
but it is short and fast, I think that...
php execute bash > bash run > bash get ip > php get ip
echo shell_exec( "dig +short myip.opendns.com #resolver1.opendns.com");
Sorry my for my english, I hope it help all you...
Reference: How can I get my external IP address in a shell script?
This is an old thread, but for what it's worth, I'm adding a simple function that I use. It uses outside services (which is inevitable it seems), but it provides a backup service as well, and local caching to avoid repetitive HTTP calls.
/*
USAGE
$ip = this_servers_public_ip(); // Get public IP, and store it locally for subsequent calls.
$ip = this_servers_public_ip(true); // Force remote query and refresh local cache if exists.
*/
function this_servers_public_ip($purge=false) {
$local = sys_get_temp_dir().'/this.servers.public.ip';
if ( $purge===true && realpath($local) ) {
unlink($local);
}
if ( realpath($local) ) {
return file_get_contents($local);
}
// Primary IP checker query.
$ip = trim( file_get_contents('https://checkip.amazonaws.com') );
if ( (filter_var($ip, FILTER_VALIDATE_IP) !== false) ) {
file_put_contents($local,$ip);
return $ip;
}
// Secondary IP checker query.
$ip_json = trim( file_get_contents('https://ipinfo.io/json') );
$ip_arr = json_decode($ip_json,true);
$ip=$ip_arr['ip'];
if ( (filter_var($ip, FILTER_VALIDATE_IP) !== false) ) {
file_put_contents($local,$ip);
return $ip;
}
return false; // Something went terribly wrong.
}
If your server have a domain name you can ping it or you can use:
$sMyServerIP = gethostbyname('yourdomain.com');
echo $sMyServerIP;
It will return your outer IP address.
Assuming your PHP is running on a Linux server you can call ifconfig using PHP's exec function. This will give public IP without need to contact some external website/service. E.g.:
$command = "ifconfig"; /// see notes below
$interface = "eth0"; //
exec($command, $output);
$output = implode("\n",$output);
if ( preg_match('/'.preg_quote($interface).'(.+?)[\r\n]{2,}/s', $output, $ifaddrsMatch)
&& preg_match_all('/inet(6)? addr\s*\:\s*([a-z0-9\.\:\/]+)/is', $ifaddrsMatch[1], $ipMatches, PREG_SET_ORDER) )
{
foreach ( $ipMatches as $ipMatch )
echo 'public IPv'.($ipMatch[1]==6?'6':'4').': '.$ipMatch[2].'<br>';
}
Note that sometimes as $command you have to specify full path of ifconfig. You can find this by executing
whereis ifconfig
from shell prompt. Furthermore $interface should be set to the name of your server's main network interface that has the link to the WAN.
On Windows you can do something similar of course, using ipconfig instead of ifconfig (and corresponding adjusted regex).
Also you could get IP via DNS A record based on hostname or server name:
$dnsARecord = dns_get_record($_SERVER['HTTP_HOST'],DNS_A);
if ( $dnsARecord ) echo 'IPv4: '.$dnsARecord[0]['ip'];
$dnsARecord = dns_get_record($_SERVER['HTTP_HOST'],DNS_AAAA);
if ( $dnsARecord ) echo 'IPv6: '.$dnsARecord[0]['ip'];
You could also use SERVER_NAME instead of HTTP_HOST if one of the two does not give what you want.
However, this is assuming that your server is configured correctly in correspondence with DNS. This may not always be the case. See my other answer using ifconfig that is perhaps better.
Have you tried:
gethostbyname(php_uname('n'));
?
I'm using the following snippet to redirect an array of IP addresses. I was wondering how I would go about adding an entire range/block of IP addresses to my dissallowed array...
<?php // Let's redirect certain IP addresses to a "Page Not Found"
$disallowed = array("76.105.99.106");
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, $disallowed)) {
header("Location: http://google.com");
exit;
}
?>
I tried using "76.105.99.*", "76.105.99", "76.105.99.0-76.105.99.255" without any luck.
I need to use PHP rather than mod_rewrite and .htaccess for other reasons.
Here's an example of how you could check a particular network/mask combination:
$network=ip2long("76.105.99.0");
$mask=ip2long("255.255.255.0");
$remote=ip2long($_SERVER['REMOTE_ADDR']);
if (($remote & $mask)==$network)
{
header("Location: http://example.com");
exit;
}
This is better than using a string based match as you can test other masks that align within an octet, e.g. a /20 block of IPs
Try the substr function:
$ip = '76.105.99.';
if (substr($_SERVER['REMOTE_ADDR'], 0, strlen($ip)) === $ip) {
// deny access
}
You can approach the problem in a different way.
If you want to ban 76.105.99.* you could do:
if (strpos($_SERVER['REMOTE_ADDR'], "76.105.99.")!==FALSE)
{
header ('Location: http://google.com');
}
Who exactly are you interested in blocking? You can use PHP or apache to block (or allow) a bunch of specific IP addresses.
If you are interested in blocking people from an entire country for example, then there are tools that give you the IP addresses you need to block. Unfortunately, it's not as simple as just specifying a range.
Check out http://www.blockacountry.com/ which generates a bunch of ip addresses you can stick in your .htaccess to block whole countries.
What you need to do is to have a test to see if a particular address lives inside a particular address range as defined by CIDR
So for instance, you need to be able to say
is 192.168.1.5
inside
192.168.1.0/24
That function is easy to write, assuming you have some basic tools to do CIDR work.
Assuming you are on a 32bit system, this class http://snipplr.com/view/15557/cidr-class-for-ipv4/
Pay attention to the IPisWithinCIDR function
It would be better to do this in apache(or any other server)
I believe that you'll need to create a for loop to add each IP address (within the range) to your array.
pseudo code
for i = 0 to 255
disallowed[i] = "76.105.99." + i
next
$blocked_ip_range_array = array('109.237.108.0','109.238.0.0');
for($i=0;$i<count($blocked_ip_range_array);$i++){
$network=ip2long($blocked_ip_range_array[$i]);
$blipr = explode(".",$blocked_ip_range_array[$i]);
if($blipr[2]=='0'){
$mask=ip2long("255.255.0.0");
}
else{
$mask=ip2long("255.255.255.0");
}
$remote=ip2long($_SERVER['REMOTE_ADDR']);
if (($remote & $mask)==$network)
{
header("Location: http://xurcun.info");
exit;
}
}
Below is a URL showing something rather similar to what Mr. Dixon and Ameer are discussing:
http://www.blackdog.ie/blog/blocking-ip-ranges-with-php/
Hope this helps.
Respectfully,
Wil