使用 php cURL 和 json 通过 ip 使用在线服务获取用户位置
Get user location by ip used online service with php cURL and json
今天我有一些 php cURL 代码必须向用户显示他的位置,例如:ip、国家、城市。如果用户是机器人 - 什么也不做。所以,我这样做,但它不能正常工作。仅显示 ip,没有其他任何内容。请帮助。。让力量与你同在。感谢大家的帮助。
<?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;
?>
不要使用 explode!,api 的答案是 JSON,而你必须这样做:
$data = json_decode($contents, true);
$country = $data['country'];
$city = $data['city'];
对于您需要的任何其他字段依此类推。
顺便说一句,您还可以使用支持 ipv4 和 ipv6 支持的多重检测的代码改进 IP 检测
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
问候并投票
首先,不要使用 explode,请改用 json_decode 然后您的 API 的 SSL 证书有问题所以请改用 http。
<?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;
今天我有一些 php cURL 代码必须向用户显示他的位置,例如:ip、国家、城市。如果用户是机器人 - 什么也不做。所以,我这样做,但它不能正常工作。仅显示 ip,没有其他任何内容。请帮助。。让力量与你同在。感谢大家的帮助。
<?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;
?>
不要使用 explode!,api 的答案是 JSON,而你必须这样做:
$data = json_decode($contents, true);
$country = $data['country'];
$city = $data['city'];
对于您需要的任何其他字段依此类推。
顺便说一句,您还可以使用支持 ipv4 和 ipv6 支持的多重检测的代码改进 IP 检测
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
问候并投票
首先,不要使用 explode,请改用 json_decode 然后您的 API 的 SSL 证书有问题所以请改用 http。
<?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;