1

I was wondering if there was a way to determine the user country name in php without any api or third party help.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294

3 Answers3

1

No, there isn't, unless you want to maintain your own database of (country, IP range) pairs.

However, if you want information about a visitor's language, an alternative solution would be to process $_SERVER['HTTP_ACCEPT_LANGUAGE']. Note that it's not a trivial task, as it can hold multiple languages (with different preferences) and it could hold unknown langauges to your program. Furthermore, this value can be manipulated by a malicious user, so the usual precautions when dealing with user input are necessary.

ljacqu
  • 2,132
  • 1
  • 17
  • 21
1

Yes, possible. But nobody suggests that way because it is not an easy task. You have to find create a database of all IP Address range with country, location, ISP etc. So, it looks like a tough job, right?

Well, fortunately, there is another way with PHP 'Geo IP Location' Package. You can download these from here as a PHP Phar Package. Then use this code:

<?php

require_once("geoip2.phar");

use GeoIp2\Database\Reader;

// Start

$reader = new Reader('/path/to/GeoLite2-Country.mmdb');
$record = $reader->country($_SERVER['REMOTE_ADDR']);

// Print/Echo

echo $record->country->isoCode . "\n");
echo $record->country->name . "\n");
echo $record->mostSpecificSubdivision->name . "\n");
echo $record->mostSpecificSubdivision->isoCode . "\n";
echo $record->city->name . "\n");
echo $record->postal->code . "\n");
echo $record->location->latitude . "\n");
echo $record->location->longitude . "\n");

?>
0

PHP has a built in GeoIP that does just that.

You might have to install it as a plugin, which should be too hard...

GeoIP

Dalai Lama
  • 404
  • 4
  • 20