【问题标题】:PHP- file_get_contents failed to open stream: Connection refusedPHP-file_get_contents 未能打开流:连接被拒绝
【发布时间】:2013-03-27 22:45:05
【问题描述】:

我正在使用以下 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);

它在这里工作正常并显示国家代码。

但它在服务器上显示错误

例子:

$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) [function.file-get-contents]:无法打开流:连接 在 /srv/disk4/1322145/www/servername.in/app/header.php 中被拒绝 在第 12 行

这有什么问题?

【问题讨论】:

  • 这可能与 PHP 关系不大,更多的是与网络限制有关。尝试在file_get_contents 之后转储$http_response_header 以获取有关失败原因的更多信息。
  • 确保您可以使用 fopen 打开一个 url。见:php.net/…
  • @MarcellFülöp :但它在 localhost 上工作仅在服务器上显示错误。那么是 $_SERVER['REMOTE_ADDR']; 的问题吗? ?
  • @MarcellFülöp : var_dump($country_code);显示布尔(假)
  • 我的意思是$http_response_header。当file_get_contents 与 HTTP 包装器一起使用时,PHP 会填充此变量,并且可能会提供有关 HTTP 请求的有用信息。

标签: php file-get-contents


【解决方案1】:

您可以使用 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;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在我的例子中,Plesk 中的Fail2Ban 扩展突然开始对发出file_get_contents() 请求的服务器进行IP 阻止。这可能不是问题,但我只是想让你意识到这种可能性。

      【讨论】:

      • 过去 5 个小时都在和这个东西作斗争。这对我有帮助。我的服务器在 postfix 上禁止了自己!它正在杀死 file_get_contents() 响应。
      • 天啊!!!!我只是花了一整天的时间来解决这个问题。您的评论解决了它!谢谢。为我节省了很多工作。我以为我必须使用 cURL 重新编码。工作了12个月,然后突然停止了。 Fail2Ban 是罪魁祸首。锁定主机服务器。再次感谢您。
      猜你喜欢
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 2011-12-19
      • 2017-09-17
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多