简体   繁体   中英

Output Country Code to console

Hi I am trying to output country code to console or pass through javascript so I can do some conditional formatting. heres my code:

<?php
  $ip = $_SERVER['REMOTE_ADDR'];
  $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
  echo("<script>console.log('PHP: ".json_encode($details->country)."');
  </script>");
?>

My output in the console is PHP: null

UPDATE

To explain my objective: I have a wp site which is being blocked in China. I have several services which I believe is issue including:

  • Google Analytics
  • Google recaptcha
  • Google Maps
  • Google Fonts
  • Vimeo

I am wanting to detect country code then if its china then do not display scripts/css in php server side.

Thanks,

How about a jQuery version of what you are trying to do. It is a lot easier than the PHP version in my opinion.

 $.getJSON("https://ipinfo.io/", function(data){ // show all options from data object //console.log(data); var country = data.country; var city = data.city; var loc = data.loc; var ip = data.ip var details = "<h1>"+ip+"</h1>"+"<br>COUNTRY: "+country+"<br>CITY: "+city+"<br>LOC: "+loc; $("#details").html(details); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="details"></div> 

There is no problem with your code so far. (You can check with a hard-coded IP address ex. 8.8.8.8 )

You are testing your code under localhost, so $_SERVER['REMOTE_ADDR'] returns the local IP Address instead of the public IP.

The site ipinfo.io will not work with local IP Addresses, so it will response something like {"ip":"192.xxx.xx.x","bogon":true} . So there is no property named country in the response, which means null .

If you deploy your code to a "real" server (which has a public IP address) then it will work.

Use ipinfo.io's official PHP client library: https://github.com/DavidePastore/ipinfo

<?php   
    // Initialize ipinfo 
    $ipInfo = new DavidePastore\Ipinfo\Ipinfo(array(
        "token" => "your_api_key" 
    ));

    $ip = $_SERVER['REMOTE_ADDR'];

    //Get all the properties
    $host = $ipInfo->getFullIpDetails($ip);

    // Output Country to JavaScript Console
    echo("<script>console.log('PHP: ".$host->getCountry()."');</script>");
?>

您需要从网址中删除大括号。

$details = json_decode(file_get_contents("http://ipinfo.io/$ip"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM