Hướng dẫn lấy địa chỉ bằng GeoIP2 (ok)

http://maxmind.github.io/GeoIP2-php

Thư viện GeoLite2-City.mmdb có thể cập nhật mới trên trang https://dev.maxmind.com/geoip/geoip2/geolite2/

Thư viện geoip2.phar có thể cập nhật mới trên trang

https://github.com/maxmind/GeoIP2-php/releases

Sau đây là ví dụ đã hoàn thành :)

Ví dụ 1: Dùng thư viện geoip2.phar

Link: https://github.com/maxmind/GeoIP2-php/releases

Link: https://www.codegrepper.com/code-examples/php/get+ip+location+php

<?php
require_once("geoip2.phar");
use GeoIp2\Database\Reader;
// City DB
$reader = new Reader('GeoLite2-City.mmdb');
echo '<pre>';
	var_export("123.20.170.47");
echo '</pre>';
$record = $reader->city("123.20.170.47");
// or for Country DB
// $reader = new Reader('/path/to/GeoLite2-Country.mmdb');
// $record = $reader->country($_SERVER['REMOTE_ADDR']);
print($record->country->isoCode . "\n");
print($record->country->name . "\n");
print($record->country->names['zh-CN'] . "\n");
print($record->mostSpecificSubdivision->name . "\n");
print($record->mostSpecificSubdivision->isoCode . "\n");
print($record->city->name . "\n");
print($record->postal->code . "\n");
print($record->location->latitude . "\n");
print($record->location->longitude . "\n");

Ví dụ 2: Dùng luôn một ví dụ có sẵn :)

Link: https://github.com/maxmind/GeoIP2-php/releases

C:\xampp\htdocs\scss\test.php

<?php
require_once 'vendor/autoload.php';
use MaxMind\Db\Reader;
$ipAddress = '123.20.170.47';
$databaseFile = 'GeoIP2-City.mmdb';
$reader = new Reader($databaseFile);
// get returns just the record for the IP address
print_r($reader->get($ipAddress));
// getWithPrefixLen returns an array containing the record and the
// associated prefix length for that record.
echo '<pre>';
	var_export($reader->getWithPrefixLen($ipAddress));
echo '</pre>';
$reader->close();

Vì 2 file GeoIP2-City.mmdb, GeoIP2-Country.mmdb có dữ liêu lớn không cho phép tải ở đây vì vậy phải tải lên google drive :)))

https://drive.google.com/file/d/1YIErxG-i2B3n67xF3FzvBTrSKmC8WofZ/view?usp=sharing

Full code có tại đây cho ví dụ này : https://drive.google.com/file/d/1rgVd2KnM7t4JorOC94Y7APKUaQGyRylv/view?usp=sharing

Last updated