maxmind / GeoIP2-php

PHP API for GeoIP2 webservice client and database reader
https://maxmind.github.io/GeoIP2-php/
Apache License 2.0
2.33k stars 276 forks source link

Calling Reader::country() returns null with City database #47

Closed daigo75 closed 9 years ago

daigo75 commented 9 years ago

I'm working on a project where we are required to geolocate visitors' country and, in some cases, visitors' city as well. Due to that, I switcher from the Country database to the City one, but I encountered an unexpected behaviour, described below:

$reader = new Reader('GeoLite2-Country.mmdb');
$country = $reader->country('87.65.122.63')->isoCode; // This returns "BE - Belgium"

$reader = new Reader('GeoLite2-City.mmdb');
$country = $reader->country('87.65.122.63')->isoCode; // This returns false

Questions

  1. Is such behaviour correct? I thought that the City database could be used for both Country and City detection.
  2. Our target is to always detect the country and, if possible, the city. If the City database can only be used for city detection, what happens if such information cannot be determined? For example, if I pass an IP Address and the city cannot be determined, how do I get the country from it?
oschwald commented 9 years ago

On recent versions of this library, calling $reader->country(...) with a City database should throw a BadMethodCallException. Use the city() method instead.

For instance, this works for me:

$reader = new Reader("/usr/local/share/GeoIP/GeoLite2-City.mmdb");
echo $reader->city('87.65.122.63')->country->isoCode;
daigo75 commented 9 years ago

That's correct, if I use city and then country it works. However, I'm worried about what would happen if the city cannot be determined. Do I still get a record with a country object?

oschwald commented 9 years ago

The methods on the reader object are for the database type, not the field type. Using the city method will return any data that is in the City database for that IP.

daigo75 commented 9 years ago

I see. If I understand it correctly, I will get all the information available for the IP address, which means:

Is that correct?

oschwald commented 9 years ago

Yes.

daigo75 commented 9 years ago

Perfect, thanks.