I recently posted how to do geo targeting with PHP with the GeoIP functions but discovered when testing something today that PHP throws an E_NOTICE notice error if the IP address does not exist in the database.
I discovered this when developing a site on my local development machine which has notices on and the $_SERVER[‘REMOTE_ADDR’] was an internal private IP address (192.168.1.200). The actual error message was this:
Notice: geoip_country_code_by_name() [function.geoip-country-code-by-name]: Host 192.168.1.200 not found in /path/to/script.php on line 138
It’s best practise to not have E_NOTICES on in a production environment so this error will not normally show in production, but it’s also best practice to have E_NOTICES on in a development environment. However it’s somewhat annoying to have this error message displayed all the time when doing development work.
There are two solutions:
1) Use the @ method to suppress the E_NOTICE for this function call, e.g.:
$country_code = @geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
2) Change the error reporting level temporarily and then revert it back again afterwards. It’s much easier to do solution (1) so it’s probably best to leave it at that. Read my get and modify the error reporting level in PHP post for more details about how to do this.
A third solution would be to use try … catch but it doesn’t work with this function.