PHP code example of timefrontiers / php-location

1. Go to this page and download the library: Download timefrontiers/php-location library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

timefrontiers / php-location example snippets


use TimeFrontiers\Location;

$location = new Location();

echo $location->ip;              // 123.45.67.89
echo $location->city;            // Lagos
echo $location->state;           // Lagos
echo $location->country;         // Nigeria
echo $location->country_code;    // NG
echo $location->currency_code;   // NGN
echo $location->currency_symbol; // ₦
echo $location->latitude;        // 6.4474
echo $location->longitude;       // 3.3903

$location = new Location('8.8.8.8');
echo $location->city; // Mountain View

$location = new Location();
// Later...
$location->refresh('1.1.1.1');

use TimeFrontiers\Location;
use TimeFrontiers\InstanceError;

$location = new Location('invalid-ip');

if (!$location->refresh()) {
    $errors = (new InstanceError($location, false))->get();
    foreach ($errors['refresh'] as $error) {
        echo $error[2]; // Error message
    }
}

$location = new Location(); // Uses ip-api.com

use TimeFrontiers\GeoIP\IpApiService;

$service = new IpApiService('your-api-key');
$location = new Location(null, $service);

use TimeFrontiers\GeoIP\GeoIPInterface;
use TimeFrontiers\GeoIP\LocationData;
use TimeFrontiers\Location;

class MyProvider implements GeoIPInterface
{
    public function locate(string $ip): LocationData
    {
        // Fetch from your API
        return new LocationData(
            ip: $ip,
            city: '...',
            region: '...',
            country: '...',
            country_code: '...',
            currency_code: '...',
            currency_symbol: '...',
            latitude: 0.0,
            longitude: 0.0
        );
    }
}

$location = new Location(null, new MyProvider());