How can PHP be utilized to determine the geographical location (city or country) of a website visitor based on their IP address?
To determine the geographical location of a website visitor based on their IP address in PHP, you can use a third-party API like MaxMind's GeoIP database. This database provides accurate location information based on IP addresses. By querying the API with the visitor's IP address, you can retrieve their city or country information and display it on your website.
$ip = $_SERVER['REMOTE_ADDR'];
// Make a request to the MaxMind GeoIP API
$response = file_get_contents("https://geoip.maxmind.com/geoip/v2.1/city/{$ip}?demo=1");
// Decode the JSON response
$data = json_decode($response, true);
// Get the city and country information
$city = $data['city']['names']['en'];
$country = $data['country']['names']['en'];
echo "You are located in $city, $country.";