How can PHP be used to log the country of origin of a user in a logfile?

To log the country of origin of a user in a logfile using PHP, you can utilize a geolocation API like MaxMind's GeoIP database. This database can provide information about the user's location based on their IP address. You can then extract the country information and write it to a logfile along with other relevant data.

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$geoip_data = file_get_contents("http://geolocation-api.com/?ip=$ip");
$geoip_info = json_decode($geoip_data, true);

$log_message = "User from " . $geoip_info['country'] . " accessed the site.";
file_put_contents('logfile.txt', $log_message . PHP_EOL, FILE_APPEND);
?>