I have some problem with db-ip.com api that display info about visitor ip's. My script only print < pre > tags but nothing between. I need that all parameters from api are decoded and print, like from this link: http://db-ip.com/178.133.109.106.
Please help me.
<?php
// get ip
if (!empty($_SERVER["HTTP_CLIENT_IP"])){
$ip = $_SERVER["HTTP_CLIENT_IP"];
}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}
else {
$ip = $_SERVER["REMOTE_ADDR"];
}
$json_url = "http://api.db-ip.com/v2/free/$ip";
$json = file_get_contents($json_url);
$json=str_replace('}, ]',"} ]",$json);
$data = json_decode($json);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
Try this code
<?php
header('Content-Type: application/json');
// get ip
$ip = $_SERVER['HTTP_CLIENT_IP'] ? $_SERVER['HTTP_CLIENT_IP'] : ($_SERVER['HTTP_X_FORWARDED_FOR'] ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']); //$ip = '178.133.109.106';
$json_url = "http://api.db-ip.com/v2/free/$ip";
$data = file_get_contents($json_url);
print_r($data);
?>
check out this link
http://tpcg.io/Gv3KLv
Related
Can someone help me please.
I can get get the host, referer, requested URI and the agent from visitors to my website but I cannot figure out how to get what response code was returned to the user.
$host = $_SERVER['REMOTE_HOST'];
$referer = $_SERVER['HTTP_REFERER'];
$requested = $_SERVER['REQUEST_URI'];
$agent = $_SERVER['HTTP_USER_AGENT'];
It must be simple but I can't seem to work it out.
FULL CODE:
$varToday = date("d-m-Y");
$filelocation = $_SERVER['DOCUMENT_ROOT']."/logs/";
$ip = getRealIpAddr();
$host = isset($_SERVER['REMOTE_HOST']) ? $_SERVER['REMOTE_HOST'] : gethostbyaddr($_SERVER['REMOTE_ADDR']);
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : "";
$referer = htmlspecialchars($referer, ENT_QUOTES, 'UTF-8');
$requested = $_SERVER['REQUEST_URI'];
$agent = $_SERVER['HTTP_USER_AGENT'];
$httpCode = http_response_code();
if ($httpCode!=200) {
$filename = $filelocation."4ECerrors".$varToday.".txt";
$content = $varDate." - ".$host." - ".$ip." - ".$requested." - ".$httpCode." - ".$referer." - ".$agent."\r";
$handle = fopen($filename, 'r');
if (filesize($filename) > 0) {
$content .= fread($handle,filesize($filename));
}
fclose($handle);
$handle = fopen($filename, 'w+');
fwrite($handle, $content,strlen($content));
fclose($handle);
}
You define the status code returned by the server, to the client (browser), via the HTTP response. There is no status code in the HTTP request.
By default PHP will return 200, but you may change it, see https://stackoverflow.com/a/12018482/135494
Today i have some php cURL code that must show to user his loacation like: ip, country, city it have.. And if the user is bot - do nothing. So, i do it like this, but it's not working properly. Only ip is shown and nothing else.. Please help.. And let the power be with you.. Thank to all for help.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "https://api.2ip.ua/geo.json?ip=$ip";
//--
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiurl");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
//--
curl_close ($ch);
//- **************-//
$pieces = explode('"', $contents);
$country = $pieces['7'];
$city = $pieces['11'];
$city2 = $pieces['13'];
echo "Your IP is :" . $ip . " and country " .$country. " and city " .$city;
?>
Don't use explode!, the answer of the api is a JSON, instead you got to do this:
$data = json_decode($contents, true);
$country = $data['country'];
$city = $data['city'];
and so on for any other field you need.
BTW you can also improve the IP detection with this code that support multiple detection with ipv4 and ipv6 support
if (isset($_SERVER['REMOTE_HOST'])) {
$ip = $_SERVER['REMOTE_HOST'];
} elseif (isset($_SERVER['HOST'])) {
$ip = $_SERVER['HOST'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$host = '';
}
$ip = str_replace("::ffff:","",$ip);//::ffff:127.127.127.127 en caso de jugo ipv6
Regards and vote up
First, don't use explode, use json_decode instead and then there is something wrong with the SSL-Certificate of your API so use http instead.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "http://api.2ip.ua/geo.json?ip=";
$contents = file_get_contents($apiurl . $ip);
$json = json_decode($contents);
$country = $json->country;
$city = $json->city;
echo "Your IP is :" . $ip . " and country " . $country . " and city " . $city;
I have created a function in PHP for fetching a YouTube video list of my channel in JSON format but I'm getting blank array.
public function channels_list()
{
$method = $_SERVER['REQUEST_METHOD'];
if($method != 'GET')
{
json_output(400,array('status' => 400,'message' => 'Bad request.'));
}
else
{
$data = array();
$json_link="https://www.googleapis.com/youtube/v3/search?key='MY API KEY'&channelId='MY CHANNEL ID'&part=snippet,id&order=date&maxResults=10";
$json = file_get_contents($this->json_link);
$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
foreach($obj['items'] as $post){
$jsondata['id'] = isset($post['id']['videoId']) ? $post['id']['videoId'] : "";
$jsondata['published_at'] = isset($post['snippet']['publishedAt']) ? $post['snippet']['publishedAt'] : "";
$jsondata['title'] = isset($post['snippet']['title']) ? $post['snippet']['title'] : "";
$jsondata['description'] = isset($post['snippet']['description']) ? $post['snippet']['description'] : "";
$jsondata['thumbnail'] = "https://i.ytimg.com/vi/{$id}/maxresdefault.jpg";
array_push($data, $jsondata);
}
json_output("200", array("list"=>$data),1);
}
}
Try this below code,I'm using this and it's working fine for me.
function get_youtube($url){
$youtube = "http://www.youtube.com/oembed?url=". $url ."&format=json";
$curl = curl_init($youtube);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($curl);
curl_close($curl);
return json_decode($return, true);
}
$url = // youtube video url
// Display Data
print_r(get_youtube($url));
Updated:
you don't need OAuth2 login for that. You can simply do it by setting your API key instead.
It's a playlistItems->list request.
Here's demonstration in api explorer: https://developers.google.com/apis-explorer/#p/youtube/v3/youtube.playlistItems.list?part=snippet&playlistId=PLjFEz-E0UPUxw3lFpnfV1dDA7OE7YIFRj&_h=2&
Instead of setting clientId and client Secret
set it's API key to your API key from cloud console in Public API access.
$client->setAPIKey($API_KEY);
Example:
$API_key = 'Your_API_Key';
$channelID = 'YouTube_Channel_ID';
$maxResults = 10;
$videoList = json_decode(file_get_contents('https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId='.$channelID.'&maxResults='.$maxResults.'&key='.$API_key.''));
how to get country name from user IP address
I have IP addresses of user i get the country name of user base on user IP address
how it is possible in php ?
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
Try this
function ip_details($IPaddress)
{
$json = file_get_contents("http://ipinfo.io/{$IPaddress}");
$details = json_decode($json);
return $details;
}
$IPaddress = 'Your ip address of user';
$details = ip_details("$IPaddress");
//echo $details->city;
echo $details->country;
//echo $details->org;
//echo $details->hostname;
For getting IP address you can use the function given by you or simply you can use
$_SERVER['REMOTE_ADDR']
to get the IP address of the user use as follow:
$ip = $_SERVER['REMOTE_ADDR']; // ip = 8.8.8.8
$country = file_get_contents('http://ipinfo.io/8.8.8.8/country'); // for more info visit [enter link description here][1]
echo $country; // output = US | UK | IN as per ip (just one country code)
Although this post has a correct answer, I have a small modification on it : using curl instead of file_get_contents because :
ipinfo.io documents suggests that.
file_get_contents doesn't have try catch pattern.
You can set a timeout request easily to prevent script waiting long for response.
Note :
Without Token, you will reach the limitation soon, so to gain free 50.000 requests/month (currently) it's better to add token in end of url :
function ip_details($ip) //return country code based on ip
{
if(empty($ip)) return "";
$url="http://ipinfo.io/{$ip}?token=XXXXX";
//trigger url
$curl = curl_init();
curl_setopt($curl, CURLOPT_TIMEOUT, 3); // wait 3 seconds to response
curl_setopt($curl, CURLOPT_URL, $url);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$json = curl_exec($curl);
if (curl_errno($curl)) {
return "";
}
//curl_close($curl);
$details = json_decode($json);
$country = (empty($details->country)) ? "" : $details->country;
return $country;
}
You can do this, which includes currency:
<?
function resolveIP($ip) {
$string = file_get_contents("https://ipsidekick.com/{$ip}");
$json = json_decode($string);
return $json;
}
$ip = '17.142.160.59';
$json = resolveIP($ip);
echo "Country name: {$json->country->name}\n";
echo "Currency name: {$json->currency->name}\n";
echo "Public holiday: {$json->currency->holiday}\n";
?>
Get Current country name and country lat long value :
$IPaddress = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
$details = $this->ip_details("$IPaddress");
$country_name = $details->country_name;
$geocode_stats = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=$country_name&sensor=false");
$output_deals = json_decode($geocode_stats);
$latLng = $output_deals->results[0]->geometry->location;
echo $lat = $latLng->lat;
echo $lng = $latLng->lng;
How can I determine a user's current location based on IP address (I guess it works this way).
<?php
$user_ip = getenv('REMOTE_ADDR');
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip"));
$country = $geo["geoplugin_countryName"];
$city = $geo["geoplugin_city"];
?>
Edited
Change freegeoip.net into ipinfo.io
<?php
function get_client_ip()
{
$ipaddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_FORWARDED'])) {
$ipaddress = $_SERVER['HTTP_FORWARDED'];
} else if (isset($_SERVER['REMOTE_ADDR'])) {
$ipaddress = $_SERVER['REMOTE_ADDR'];
} else {
$ipaddress = 'UNKNOWN';
}
return $ipaddress;
}
$PublicIP = get_client_ip();
$json = file_get_contents("http://ipinfo.io/$PublicIP/geo");
$json = json_decode($json, true);
$country = $json['country'];
$region = $json['region'];
$city = $json['city'];
?>
<?php
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
echo $data . "<br>";
}
?>
Try this code using this source. *It works!
Try this code using the hostip.info service:
$country=file_get_contents('http://api.hostip.info/get_html.php?ip=');
echo $country;
// Reformat the data returned (Keep only country and country abbr.)
$only_country=explode (" ", $country);
echo "Country : ".$only_country[1]." ".substr($only_country[2],0,4);
As PHP relies on a server, the real-time location can’t be provided. Only a static location can be provided. It is better to avoid to rely on the JavaScript for a location rather than using PHP.
But there is a need to post the JavaScript data to PHP, so that it can easily be accessible to a program on the server.
An IP address gives you a quite unreliable location. You could Ajax the location upon load with JavaScript if it isn't critical to have the location at first. (Also, the user needs to give you its permission to access it.)
HTML5 Geolocation
The old freegeoip API is now deprecated and will be discontinued on 2018-07-01.
The new API is from ipstack. You have to create the account in ipstack. Then you can use the access key in the API URL.
$url = "http://api.ipstack.com/122.167.180.20?access_key=ACCESS_KEY&format=1";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response);
$city = $response->city; // You can get all the details like longitude, latitude from the '$response'.
For more information, check at freegeoip (GitHub).