【发布时间】:2020-06-21 09:24:40
【问题描述】:
我有一个名为 assets 的类,在 assets 类中存在许多函数,但有些函数没有按我预期的那样工作。
这是我的代码
<?php
class assets
{
function curl_get_contents($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
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;
}
function getCountry($ip){
$PublicIP = $this->get_client_ip();
$json = $this->curl_get_contents("http://ipinfo.io/".$PublicIP."/geo");
$json =json_decode($json, true);
$country = $json['country'];
return $country;
}
function getRegion($ip){
$PublicIP = $this->get_client_ip();
$json = $this->curl_get_contents("http://ipinfo.io/$PublicIP/geo");
$json =json_decode($json, true);
$region = $json['region'];
return $region;
}
function getCity($ip){
$PublicIP = $this->get_client_ip();
$json = $this->curl_get_contents("http://ipinfo.io/$PublicIP/geo");
$json =json_decode($json, true);
$city = $json['city'];
return $city;
}
}
$assets = new assets();
$ip = $assets->get_client_ip();
echo($ip);
$city = $assets->getCountry($ip);
?>
输出
abc.pq.wx.yz// no output for country
出于安全考虑,我将此输出写入此表单,但 IP 地址正确
这个代码只给了我 IP 地址,但这个代码没有给出县区域和城市。当我尝试手动调用 Api 时,我得到了预期的结果。
【问题讨论】:
-
并在函数中注释
return。那你期待什么? -
@u_mulder 抱歉,
return没有评论真实代码,By mistake我在帖子中评论了return -
旁注: 与其向 API 发出多个相同的请求,不如调用它一次并重用相同的响应。每个电话都有开销。
-
$city = $assets->getCountry($ip);有点不合逻辑!你不输出$city??喜欢echo $city; -
@RiggsFolly 非常感谢你提醒我的错误
标签: php api class geolocation