PHP-文件\u获取\u内容无法打开流:连接被拒绝

PHP-文件\u获取\u内容无法打开流:连接被拒绝,php,file-get-contents,Php,File Get Contents,我正在使用以下API获取使用IP的国家/地区代码 http://api.hostip.info/country.php?ip=' . $IP 示例:在本地主机上 $IP = '202.71.158.30'; //pass the ip as a parameter for follow URL it will return the country $country_code = file_get_contents('http://api.hostip.info/country.php?ip

我正在使用以下API获取使用IP的国家/地区代码

http://api.hostip.info/country.php?ip=' . $IP
示例:在本地主机上

$IP = '202.71.158.30';

//pass the ip as a parameter for follow URL it will return the country

$country_code = file_get_contents('http://api.hostip.info/country.php?ip=' . $IP);
在这里工作很好,并显示国家代码

但它在服务器上显示错误

例如:

$IP=$_SERVER['REMOTE_ADDR'];

$country_code = file_get_contents('http://api.hostip.info/country.php?ip=' . $IP);
显示以下错误:

警告: 文件获取内容() [function.file get contents]:无法打开流:连接 在/srv/disk4/1322145/www/servername.in/app/header.php中被拒绝 在线12


这有什么问题?

您可以使用CURL代替file\u get\u contents()


某些服务器不允许通过您请求中的IP地址进行访问。

您可以使用
CURL
来防止此问题。

在我的例子中,Plesk中的
Fail2Ban
扩展突然启动了IP阻止执行
文件获取内容()请求的服务器。这可能不是问题,但我只是想让你意识到这种可能性

这可能与PHP关系不大,而与网络限制关系更大。尝试在
文件\u get\u contents
之后转储
$http\u response\u header
,以获取有关失败原因的详细信息。确保可以使用fopen打开url。请参阅:@MarcellFülöp:但它只在本地主机上工作,服务器上显示错误。那么这就是$_SERVER['REMOTE_ADDR']的问题了吗@MarcellFülöp:var_dump(国家代码);显示bool(false)我的意思是
$http\u response\u header
。当HTTP包装器使用
file\u get\u contents
时,该变量由PHP填充,可能会提供有关HTTP请求的有用信息。在过去的5个小时里,我们一直在处理这个问题。这对我有帮助。我的服务器在postfix上禁止自己!它正在终止文件\u get\u contents()响应。
<?php
    $IP = '202.71.158.30'; 
    $runfile = 'http://api.hostip.info/country.php?ip=' . $IP;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $runfile);

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec ($ch);

    curl_close ($ch); 

    echo $content;