0
$address = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

if (strpos($address, 'localhost') == false) {
    $stack = explode('/', $_SERVER["REQUEST_URI"]);
    $page = array_pop($stack);

    $ip = $_SERVER['REMOTE_ADDR'];
    $query = @unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
    $country = $query['country'];
    $city = $query['city'];
    $isp = $query['isp'];

    if (!$ip == 'IPADDRESS') {
        try {
            $sql = "insert into stat (country, city, isp, ip, page) values (:acountry, :acity, :aisp, :aip, :apage)";
            $st = $db->prepare($sql);
            $st->execute([
                ":acountry" => $country,
                ":acity" => $city,
                ":aisp" => $isp,
                ":aip" => $ip,
                ":apage" => $page
            ]);
        }
        catch(PDOException $e) {
            echo $e->getMessage();
        }
    }
}

Sometimes this doesn't work. Data are not inserted into database.

Is it possible that the reason is mobile visiting or maybe Chrome incognito mode or... what?

Edwin
  • 1,135
  • 2
  • 16
  • 24
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • Possible duplicate "PHP $_SERVER['REMOTE_ADDR'] empty" [from here](https://stackoverflow.com/questions/18005012/php-serverremote-addr-empty). – camelsWriteInCamelCase Nov 10 '17 at 07:49
  • Geolocation databases are not always complete, some IPs don't have a known location. – Barmar Nov 10 '17 at 08:16
  • What is the reason for the line `if (!$ip == 'IPADDRESS')`? Note that the `!` operator returns `true` or `false`, which can never be equal to the string 'IPADDRESS' – Karsten Koop Nov 10 '17 at 08:37
  • "Is it possible that the reason is mobile visiting or maybe Chrome incognito mode?": No, the code runs on the server, so as long as a request is made, the script runs and has an IP address. It could only happen if the mobile version of the site does not run this script. Where is the code placed? Inside your script that creates the html, or called from there? – Karsten Koop Nov 10 '17 at 08:39
  • 2
    The comments already describe 3 reasons this would fail. One more - doing an http request to a remote site (http://ip-api.com/) could fail, timeout, or just not complete before your visitor browses away to another page. Does not seem like a good approach. Save the IP immediately, and do lookups later. – Don't Panic Nov 10 '17 at 08:50
  • I'm waiting a summarize answer to accept it. – qadenza Nov 10 '17 at 10:47

0 Answers0