Reputation:
Introduction
I have written following PHP
code to find location based on IP address
. But this code works properly at client side and does not work on server. What may be the problem?
Code
echo $ip = $_SERVER['REMOTE_ADDR'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}/json"));
echo "<br>".$details->country;
echo "<br>".$details->region;
echo "<br>".$details->city;
echo "<br>".$details->loc;
echo "<br>".$details->postal;
echo "<br>".$details->org;
Problem
This code only shows ip address
(executed first line only) and not showing any other details of location.
Upvotes: 2
Views: 689
Reputation: 1
Official PHP library for IPinfo (IP geolocation and other types of IP data): https://github.com/ipinfo/php/
Upvotes: -1
Reputation: 1062
Your server's IP address can be found as follows:
echo $_SERVER['SERVER_ADDR'];
$_SERVER['REMOTE_ADDR'];
gives you client or requesting browser/machine's IP address.
Upvotes: -1
Reputation: 6647
Not seeing your error message, I'm going to go ahead and assume file_get_contents
has been blocked.
CURL the url, much more reliable.
<?php
echo $ip = $_SERVER['REMOTE_ADDR'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => "http://ipinfo.io/{$ip}/json"
));
$details = json_decode(curl_exec($curl));
curl_close($curl);
echo "<br>".$details->ip;
echo "<br>".$details->country;
echo "<br>".$details->region;
echo "<br>".$details->city;
echo "<br>".$details->loc;
echo "<br>".$details->postal;
echo "<br>".$details->org;
Upvotes: 5