Reputation: 311
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?
Upvotes: 2
Views: 6426
Reputation: 11334
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.
Upvotes: 0
Reputation: 3820
I've been needing the GeoIP
services 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
Upvotes: 1
Reputation: 13257
$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); ?>" />
Upvotes: 11
Reputation: 163488
$pageContent = file_get_contents('http://freegeoip.net/json/' . $_SERVER['REMOTE_ADDR']);
No need to echo into a string parameter... just concatenate with .
.
Upvotes: 2