Skip to content

Instantly share code, notes, and snippets.

@mylk
Created August 14, 2016 16:32
Show Gist options
  • Save mylk/d0f13f6fddbabf8968d51cee9817a597 to your computer and use it in GitHub Desktop.
Save mylk/d0f13f6fddbabf8968d51cee9817a597 to your computer and use it in GitHub Desktop.
Symfony Geolocation service using geoplugin.net
<?php
/*
* Installation (Symfony):
* =======================
* # services.yml
* services:
* # ...
* acme.geoip:
* class: Acme\AcmeBundle\Service\GeoIpService
*
* Usage (Symfony):
* ================
* $geoIp = $this->get("acme.geoip");
* $response = $geoIp->locate();
*/
namespace Acme\AcmeBundle\Service;
use Symfony\Component\HttpFoundation\RequestStack;
class GeoIpService
{
private $request;
public function setDependencies(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
}
public function locate()
{
$result = null;
$clientIp = $this->request->getClientIp();
// doesn't filter loopback ip
if (\filter_var($clientIp, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
$response = \json_decode(\file_get_contents("http://www.geoplugin.net/json.gp?ip=$clientIp"));
if (
$response
&& \property_exists($response, "geoplugin_status")
&& \in_array($response->geoplugin_status, array(200, 206))
) {
$result = array(
"city" => $response->geoplugin_city,
"state" => $response->geoplugin_regionName,
"state_code" => $response->geoplugin_regionCode,
"country" => $response->geoplugin_countryName,
"country_code" => $response->geoplugin_countryCode,
"continent_code" => $response->geoplugin_continentCode,
"longitude" => $response->geoplugin_longitude,
"latitude" => $response->geoplugin_latitude
);
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment