PHP GeoIP causing 500 error

135

I'm very confused with this issue but I was attempting to detect a users IP address and perform a redirect based on the users country code. In order to do this I used the following piece of code:

$url = $_SERVER['REQUEST_URI'];
require_once("geoip.inc");
$gi = geoip_open("GeoIP.dat", GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
if ($country != "GB" && strpos($url, '/?') === false) {
   if ($country_code == "IE") {
      header("Location: https://www.mymainsite.com");
      die();
   } else {
      header("Location: http://www.othersite.com");
      die();
   }
}

However each time I run the code I get a 500 Server error. I've managed to narrow down the line of code that is causing it:

require_once("geoip.inc");

If I remove this line the problem is gone but obviously I need the file as it's crucial to the geolocation.

Would anyone have any idea as to why it could be throwing a 500 error?

Many thanks

256

Answer

Solution:

I am posting this for anyone who is looking to implement geoip functionality on their site but runs into a similar issue.

The reason for the above error is due to the fact that the filegeoip.inc is loaded in an environment where thegeoip extension is enabled.

Bothgeoip.inc and thegeoip extension declare a method with the same name resulting in a conflict. Ideally there should be a check before calling the function to see if it exists which can be done like so:

if (!function_exists('geoip_country_name_by_name')) {
    function geoip_country_name_by_name($gi, $name) {
        $country_id = geoip_country_id_by_name($gi, $name);
        if ($country_id !== false) {
            return $gi->GEOIP_COUNTRY_NAMES[$country_id];
        }
        return false;
    }
}

Just simply wrap the offending function in theìf statement:

if(!function_exists('name_of_function')){.....}

and the problem is rectified.

I also should mention that @MikePurcells suggestion of looking through the server logs helped big time. My development server is an Apache Server running linux Redhat. The logs are located in /var/log/httpd/error_log. That's where I checked and discovered this error:

[Wed Oct 28 15:49:33 2015] [error] [client xx.xxx.xxx.xx] PHP Fatal error:  Cannot redeclare geoip_country_code_by_name()

Hope that helps anyone.

People are also looking for solutions to the problem: php - CakePHP 2.5.7 - Authentication failure on login with non-standard user

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.