Very hacky way to get client’s country code based on IP

You’d think that by now there should be an easier way to accomplish something like this.
(i.e. Send a client IP to some service, and get their country or other location information).

All my research just pointed to some some API’s, complicated components and way to much extra leg work to achieve something seemingly simple.

Note, I need to take care of this on the server side, thus I couldn’t fully leverage google’s JSAPI.

Yet, I could do the following:

public function getClientCountry() {
    App::import('Core', 'HttpSocket');
    $HttpSocket = new HttpSocket();
    $response = preg_split('/"country_code":"/', $HttpSocket->get(''));
    return substr($response[1], 0, 2);

Simply load the above URL in your browser to see the actual response…
Once I get the full response back, I hack my way to “extract” the value. Blah.

p.s. If someone has better alternatives, please share. Thanks ;)

Related Posts