Skip to content

Instantly share code, notes, and snippets.

@svandragt
Created April 11, 2014 10:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svandragt/10455833 to your computer and use it in GitHub Desktop.
Save svandragt/10455833 to your computer and use it in GitHub Desktop.
SvdGeolocationService
<?php
/**
* This helper is a minimal geolocation service wrapper that allows quick geolocating.
*
* freegeoip.net is community funded, therefore please consider donating if you like and use this service.
* Alternatively you can run your own server.
*
* Example (uses a 1 hour cookie to minimize lookups):
* $is_international = Cookie::get('IsInternational');
* if (is_null($is_international)) {
* $geo = new SvdGeolocationService();
* $is_international = !$geo->fromCountryCode('GB');
* Cookie::set("IsInternational", $is_international, 1/24);
* }
* if ($is_international) {$this->redirect('/international-home', 302);}
*
*
*/
class SvdGeolocationService extends RestfulService {
private $json;
/**
* Construct connection to geo location service
* @param string $ip ip address to lookup
* @param integer $expiry how many seconds the request is cached to disk
*/
public function __construct(String $ip=null, $expiry=3600){
if (is_null($ip)) {
$ip = $_SERVER['REMOTE_ADDR'];
}
$format = "json";
$url = "https://freegeoip.net/$format/$ip";
$this->checkErrors = true;
parent::__construct($url,$expiry);
$this->json = $this->requestBody();
}
/**
* Return the country code
* @return string country code
*/
public function countryCode() {
return (string) $this->json['country_code'];
}
/**
* Check if the located matches the supplied country code
* @param string $country_code supplied country coe
* @return bool
*/
public function fromCountryCode(String $country_code) {
$geo_countrycode = $this->countryCode();
return (bool) (strtolower($geo_countrycode) == strtolower($country_code));
}
/**
* Return the body of the request as an array
* @return array
*/
private function requestBody() {
$body = $this->request()->getBody();
$a = Convert::json2array($body);
return (array)$a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment