2

I'm trying to display the users country (based on their IP) in a form input value.

Here's my code so far ..

<input style="display:block" type="text" name="country" id="country" value="<?php               
$pageContent = file_get_contents('http://freegeoip.net/json/echo $_SERVER['REMOTE_ADDR']');
$parsedJson  = json_decode($pageContent);
echo $parsedJson->country_name; ?>" />

I'm using PHP JSON-decode to get the data from "http://freegeoip.net/json/(IP ADDRESS)".

That website geocodes the IP address and returns a country name.

What I want to do is to be able to substitute in a users IP address into that web address, which would then return the country name of the user. The best way I could think of was by using

<?php echo $_SERVER['REMOTE_ADDR']; ?> 

but when I put it in I get a Server Error.

How would I go about doing this?

user990175
  • 191
  • 5
  • 12

4 Answers4

11
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']);

You can't use echo within a function. Instead, you should use the concatenating operator.

Also, better code would be something like this:

<?php               
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']);
$parsedJson  = json_decode($pageContent);
?>
<input style="display:block" type="text" name="country" id="country" value="<?php echo htmlspecialchars($parsedJson->country_name); ?>" />
Brad
  • 159,648
  • 54
  • 349
  • 530
Jeroen
  • 13,056
  • 4
  • 42
  • 63
2
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']);

No need to echo into a string parameter... just concatenate with ..

Brad
  • 159,648
  • 54
  • 349
  • 530
1

I've been needing the GeoIPservices myself in some project lately. I've created a ** PHP wrapper**, in case others are looking for a PHP helper for this.

Can be found at https://github.com/DaanDeSmedt/FreeGeoIp-PHP-Wrapper

daan.desmedt
  • 3,752
  • 1
  • 19
  • 33
0

Since Freegeoip will became a paid service (https://ipstack.com/), if you want a free simple service you can use ip-api.com instead of freegeoip.net :

function getDataOfIp($ip) {
    try {
        $pageContent = file_get_contents('http://ip-api.com/json/' . $ip);
        $parsedJson  = json_decode($pageContent);
        return [
            "country_name" => $parsedJson->country,
            "country_code" => $parsedJson->countryCode,
            "time_zone" => $parsedJson->timezone
        ];
    } 
    catch (Exception $e) {
        return null;
    }
}

You should adapt return value by the data you need.

Samuel Dauzon
  • 10,744
  • 13
  • 61
  • 94