Getting visitors country from their IP using PHP, cURL and JSON
IPinfo Lite
Accurate, reliable country-level geolocation data updated daily.
API Access
Use your API token to make unlimited requests. Send it as HTTP Basic Auth, a bearer token, or a URL parameter.
Official website: https://ipinfo.io/
Using the IPinfo Lite API service, you can access the API from an IPv4 connection explicitly:
URL to use for cURL: https://v4.api.ipinfo.io/lite/YOURIPADDRESS?token=YOURTOKEN
// Set the IP address
$ipaddr = $_SERVER['REMOTE_ADDR'];
// Set the API endpoint
$endpoint = "https://v4.api.ipinfo.io/lite/".$ipaddr."?token=YOURTOKEN";
// Initialize curl session
$curl = curl_init($endpoint);
// Set curl options to return the response as a string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Execute the session, making the request
$response = curl_exec($curl);
// Close the cURL session
curl_close($curl);
// Convert JSON string into a PHP object
$json = json_decode($response);
// Print some details of the API by accessing object properties
echo "Data for $ip:" . "
";
echo "ASN: $json->asn" . "
";
echo "AS Name: $json->as_name" . "
";
echo "AS Domain: $json->as_domain" . "
";
echo "Country Code: $json->country_code" . "
";
echo "Country: $json->country" . "
";
echo "Continent Code: $json->continent_code" . "
";
echo "Continent: $json->continent" . "
";