Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IP Geocode using PHP echo

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?

like image 406
user990175 Avatar asked Dec 09 '25 06:12

user990175


2 Answers

$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); ?>" />
like image 102
Jeroen Avatar answered Dec 11 '25 20:12

Jeroen


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

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

like image 33
Brad Avatar answered Dec 11 '25 21:12

Brad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!