我制作了读取我的网站的GeoPlugin数据的功能,在一台服务器上我发现了奇怪的问题。所有 cURL 请求都将被拒绝。这是我代码的一部分:
protected $url='http://www.geoplugin.net/json.gp?ip={IP}&base_currency={CURRENCY}';
protected function __get_data($ip=false, $currency='')
{
// Current or custom IP
$ip = ((is_bool($ip) && $ip==false) ? $this->__ip() : $ip);
if($ip!='127.0.0.1' || $ip!='0.0.0.0')
{
// Configure GET function
$url = str_replace('{IP}', $ip, $this->url );
if(empty($currency))
$url = str_replace( '&base_currency={CURRENCY}', '', $url);
else
$url = str_replace( '{CURRENCY}', $currency, $url);
// Get content from URL
if(function_exists("curl_init"))
{
$cURL = curl_init();
curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_CONNECTTIMEOUT ,5);
curl_setopt($cURL, CURLOPT_TIMEOUT , 2);
curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($cURL);
curl_close($cURL);
}
else
{
$result = file_get_contents($url);
}
// Return objects from JSON data
if($result!=false)
{
return json_decode($result);
}
else return false;
}
else return false;
}
## find real IP adress of visitor ##
protected function __ip()
{
$findIP=array(
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR'
);
$ip = '';
foreach($findIP as $http)
{
if(function_exists("getenv"))
{
$ip = getenv($http);
}
else
{
if (array_key_exists($http, $_SERVER) !== false){
foreach (explode(',', $_SERVER[$http]) as $findIP){
$ip = trim($findIP);
}
}
}
if(function_exists("filter_var") && !empty($ip))
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) return $ip;
}
else if(preg_match('/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/', $ip) && !empty($ip))
{
return $ip;
}
}
return '0.0.0.0';
}
在arround90网站上,一切都完美运行,在一个有var_dump()
的网站上,我发现连接被拒绝。我也尝试了file_get_contents
和相同的结果。我也尝试在一些与网站分开的测试 PHP 文件中调用 cURL 并得到相同的结果。可能是什么问题?
-
这可能是DNS问题;
-
可能是连接不良(加载需要更多时间);
您的查询 可能会被目标服务器禁止,因为来自您的 IP(源的服务器 IP)的查询在一段时间内过多,超过了限制。
您可以执行的操作:
-
确保您可以在不使用cURL的情况下从源服务器打开目标URL(如果您使用简单托管,我的意思是不是VPS,您将无法检查它);
-
增加CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT的值;
-
如果问题无法解决,您应该将代理与 cURL 一起使用(查找有关CURLOPT_PROXY的官方文档以及curl_setopt函数的其他代理选项)。
cURL 可能在服务器中被禁用。
请运行 phpinfo() 来检查 cURL 的状态。
如果它被禁用,请安装 cURL 并在 PHP 中启用它。