Paket ini menyediakan pustaka PHP yang menentukan negara alamat IP.
Anda dapat dengan mudah menginstal geolokasi PHP dengan komposer.
composer require divineomega/php-geolocation
Penggunaan geolokasi PHP yang paling sederhana adalah membuat objek Locator baru dan memanggil metode getCountryByIP -nya.
// Get country of the current request's IP address
$ country = ( new Locator )-> getCountryByIP ( $ _SERVER [ ' REMOTE_ADDR ' ]);
// Get country of a specific IP address
$ country = ( new Locator )-> getCountryByIP ( ' 93.184.216.34 ' );
// Returns a Country object
/*
object(DivineOmegaCountriesCountry)#4693 (16) {
["name"]=>
string(13) "United States"
["officialName"]=>
string(24) "United States of America"
// etc...
}
*/ Anda dapat mengonfigurasi geolokasi PHP untuk menggunakan pustaka caching PSR-6 yang sesuai. Ini mudah dilakukan dengan menggunakan metode setCache .
Contoh berikut mengonfigurasi cache file (disediakan oleh paket cache/filesystem-adapter ).
use League Flysystem Adapter Local ;
use League Flysystem Filesystem ;
use Cache Adapter Filesystem FilesystemCachePool ;
$ filesystemAdapter = new Local ( __DIR__ . ' / ' );
$ filesystem = new Filesystem ( $ filesystemAdapter );
$ cachePool = new FilesystemCachePool ( $ filesystem );
$ locator = new Locator ;
$ locator -> setCache ( $ cachePool );
$ country = $ locator -> getCountryByIP ( ' 93.184.216.34 ' ); Secara default, geolokasi PHP akan mencoba menggunakan perintah whois asli sistem operasi untuk menentukan alamat IP. Jika Anda berharap dapat menggunakan penyedia lokasi alternatif. Ini dapat dilakukan dengan menggunakan metode setLocationProvider , sebagai berikut.
$ locator = new Locator ;
$ locator -> setLocationProvider ( new IpStack ( ' my_ip_stack_api_key ' );
$ country = $ locator -> getCountryByIP ( ' 93.184.216.34 ' );Untuk mendapatkan kunci API gratis, daftar di situs web IP Stack.
Jika Anda ingin mengembangkan penyedia lokasi Anda sendiri, cukup buat kelas baru yang mengimplementasikan LocationProviderInterface yang disediakan dalam paket ini. Lihat kelas penyedia lokasi WhoIs dan FreeGeoIP yang ada jika Anda perlu bantuan membuat penyedia lokasi Anda sendiri.