Torann / laravel-geoip

Determine the geographical location of website visitors based on their IP addresses.
http://lyften.com/projects/laravel-geoip
BSD 2-Clause "Simplified" License
2.07k stars 372 forks source link

DB-IP: free database #212

Open Artem-Schander opened 2 years ago

Artem-Schander commented 2 years ago

This is for everyone looking for a completely free database (as far as i can see also for commercial use) https://db-ip.com/db/download/ip-to-city-lite Needs to be said: The city accuracy is not that good

Here is the corresponding service:

<?php

namespace App\Services\GeoIP;

use PharData;
use Exception;
use GeoIp2\Database\Reader;
use Torann\GeoIP\Services\MaxMindDatabase;

class DBIP extends MaxMindDatabase
{
    /**
     * Update function for service.
     *
     * @return string
     * @throws Exception
     */
    public function update()
    {
        if ($this->config('database_path', false) === false) {
            throw new Exception('Database path not set in config file.');
        }

        $this->withTemporaryDirectory(function ($directory) {
            $gzFile = sprintf('%s/dbip-city-lite.gz', $directory);

            file_put_contents($gzFile, fopen($this->config('update_url'), 'r'));

            $file = gzopen($gzFile, 'rb');
            $outFile = fopen($this->config('database_path'), 'wb');
            while (!gzeof($file)) fwrite($outFile, gzread($file, 4096));

            fclose($outFile);
            gzclose($file);
        });

        return "Database file ({$this->config('database_path')}) updated.";
    }
}

and the config:

    'services' => [

        'db_ip' => [
            'class' => \App\Services\GeoIP\DBIP::class,
            'database_path' => storage_path('app/geoip.mmdb'),
            'update_url' => sprintf("https://download.db-ip.com/free/dbip-city-lite-%s-%s.mmdb.gz", date('Y'), date('m')),
            'locales' => ['en'],
        ],

        // ...
    ],
Artem-Schander commented 2 years ago

@Torann sorry for the noise, but I thought it would be nice for others to skip the extra work :)