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?
$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); ?>" />