file_get_contents打开流失败:连接被拒绝


PHP- file_get_contents failed to open stream: Connection refused

我使用以下API获取使用IP的国家代码

http://api.hostip.info/country.php?ip=' . $IP
示例:在Localhost
$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);

和它在这里工作良好,并显示国家代码。

但是Server

的例子:

$IP=$_SERVER['REMOTE_ADDR'];
$country_code = file_get_contents('http://api.hostip.info/country.php?ip=' . $IP);

显示以下错误:

警告:file_get_contents (http://api.hostip.info/country.php?ip=101.63.xx.xxx)(函数。file-get-contents]:打开流:连接失败在/srv/disk4/1322145/www/servername.in/app/header.php中拒绝第12行

这有什么问题?

您可以使用CURL来代替file_get_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;

使用curl方法代替file_get_contents()

它不工作在localhost在google.com。使用其他引擎或使用curl:

创建一个函数或在同一个函数中使用:

我更喜欢在函数中使用它,以避免将来重复。

$IP = '202.71.158.30';
$country_code = file_get_contents_fun('http://api.hostip.info/country.php? 
ip='.$IP);
public function file_get_contents_fun($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT,30);
    $content = curl_exec ($ch);
    curl_close ($ch); 
    return $content;
}

某些服务器不允许通过您的请求中的IP地址访问。您可以使用CURL来防止这个问题。

在我的情况下,Plesk中的Fail2Ban扩展突然开始ip阻塞做file_get_contents()请求的服务器。这可能不是问题,但我只是想让你意识到这种可能性。

在file_get_contents中添加可选参数,使用stream_context_create函数打开有效的流连接

$context = stream_context_create([
    'http' => ['protocol_version' => '1.1'],
]);
$result = file_get_contents($url, false, $context);
var_dump($result);