PHP GeoIP functions throw notices if the IP address is not found
Posted August 20th, 2009 in PHP
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.
The Error
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
The Solution
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.
Related posts:
- PHP geo targeting with the geoip functions (Thursday, August 13th 2009)
- Get and modify the error reporting level in PHP (Thursday, July 23rd 2009)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
