我有一个名为
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
时,我得到了预期的结果。
在你的
getCountry()
函数中你已经返回了值,但你仍然没有打印它。
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'];
retun $country;
}
$city = $assets->getCountry($ip);
echo $city;
注意
如果您没有在实现中使用它,为什么要将
$ip
传递到 getCountry()
?