0

I have this ip logger php script, it works well, but I need to add the country name in each log.. How can I do that?

<?php

$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$dateTime = date('Y/m/d G:i:s');
$file = "visitors.html";
$file = fopen($file, "a");
$data = "<pre><b>User IP</b>: $ip <b> Browser</b>: $browser <br>on Time : $dateTime <br></pre>";
fwrite($file, $data);
fclose($file);
echo "<h1>Hi :)</h1>";
?> 
Azad
  • 5,144
  • 4
  • 28
  • 56

1 Answers1

0
<?php

$ip = "8.8.8.8";

$ip_info = json_decode(file_get_contents("http://ip-api.com/json/$ip"), true);

echo "<pre>";
echo print_r($ip_info, true);
echo "</pre>";

?>

You should be getting output as :

Array
(
    [as] => AS15169 Google LLC
    [city] => Mountain View
    [country] => United States
    [countryCode] => US
    [isp] => Google
    [lat] => 37.4229
    [lon] => -122.085
    [org] => Google
    [query] => 8.8.8.8
    [region] => CA
    [regionName] => California
    [status] => success
    [timezone] => America/Los_Angeles
    [zip] => 
)

Here with your code it will be something like this as :

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$ip_info = json_decode(file_get_contents("http://ip-api.com/json/$ip"), true);
$country = $ip_info['country'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$dateTime = date('Y/m/d G:i:s');
$file = "visitors.html";
$file = fopen($file, "a");
$data = "<pre><b>User IP</b>: $ip <b> Browser</b>: $browser <br>on Time : $dateTime <br>from Country : $country</pre>";
fwrite($file, $data);
fclose($file);
echo "<h1>Hi :)</h1>";
?>
Umair Shah
  • 2,305
  • 2
  • 25
  • 50