Reputation: 2459
I would like to detect users country, so to preselect it in drop-down list in my php form. I tried to do it by getting users ip address and then I used Maxmind Geoip to get country name from ip. Everything works fine except when user is behind vpn, and this is when I cannot get the real ip (and so the country) of user if he/she is behind proxy or use VPN.
I read some similar post such as How to get Real IP from Visitor? and What is the most accurate way to retrieve a user's correct IP address in PHP?, and tried $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_X_FORWARDED_FOR'], getenv('REMOTE_ADDR'), etc. but none of them returned original ip when I am behind vpn.
I am really interested to know if there is any way to get the user real ip (e.g I am very curious to know how some websites like http://whatismyip.com return the original ip?). If really it is not possible to obtain this original ip in php as is said in this post, is there any other way to detect user country? (I also thought about browser language, but I think it would not be useful in my case, since e.g many users might set it to English while they belong to other countries)
Any idea would be highly appreciated,
Upvotes: 1
Views: 1204
Reputation: 1213
Because IP blocks are being constantly moving through ISPs it is not an easy task to gather up-to-date database for your applications.
Here is an example with one of the free APIs:
function get_ip_details($ip_address)
{
//function to find country, city and country code from IP.
//verify the IP.
ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : "";
//get the JSON result from hostip.info
$result = file_get_contents("http://api.hostip.info/get_json.php?ip=".$ip_address);
$result = json_decode($result, 1);
//return the array containing city, country and country code
return $result;
}
The result would be something similar to this json response
Also, most modern web browsers have this future already built-in, so you can get the user's country on-the-fly without 3rd party APIs: Demo
Edit: In OPs case it is impossible to recognize user's country.
Upvotes: 0
Reputation: 31
Theoretically it is always possible to track down a ip if you have access to ISP's etc.. However, from a programmers perspective there is no certain way to know the visitors real ip address hence you will never have 100% accuracy. There are things you can do to improve accuracy such as you have suggested $_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_X_FORWARDED_FOR']. Perhaps someone else can help you crack down on more methods that will improve accuracy
Upvotes: 0