PHP code example of danielme85 / laravel-geoip2

1. Go to this page and download the library: Download danielme85/laravel-geoip2 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/ */

    

danielme85 / laravel-geoip2 example snippets


 
 use danielme85\Geoip2\Facade\Reader;
 ...
 
 function getLocation(Request $request) {
    $reader = Reader::connect();
    /*
    I was experiencing inaccurate results... until I remembered that my web server traffic was routed trough CloudFlare :p
    In that case CloudFlare provides the original client ip in the following header information.
    */   
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        $ip = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    else {
        $ip = $request->ip();
    }
    //the city() function from the GeoIp2 Php API will throw an exception if the ip-address is not found in the DB.
    try {
        $geodata = $reader->city($ip)->jsonSerialize(); //jsonSerialize seems to actually return an associative array.
    }
    catch (\Exception $e) {
        Log::warning($e->getMessage());
        return response()->json("Geo-location not found!", 500);
    }

    return response()->json($geodata);
}
 

php artisan vendor:publish --provider="danielme85\Geoip2\Geoip2ServiceProvider"
  

 php artisan geoip:download