PHP-file_get_contents 无法打开流:连接被拒绝

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15835274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:03:27  来源:igfitidea点击:

PHP- file_get_contents failed to open stream: Connection refused

phpfile-get-contents

提问by J.K.A.

I am using the following API for getting the country code using IP

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

http://api.hostip.info/country.php?ip=' . $IP

Example: on 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);

and its working fine here and showing the country code.

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

But it showing error on Server

但它在服务器上显示错误

Example:

例子:

$IP=$_SERVER['REMOTE_ADDR'];

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

Showing following error:

显示以下错误:

Warning: file_get_contents(http://api.hostip.info/country.php?ip=101.63.xx.xxx) [function.file-get-contents]: failed to open stream: Connection refused in /srv/disk4/1322145/www/servername.in/app/header.php on line 12

警告: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 行

Whats wrong with this?

这有什么问题?

回答by Pankaj Dadure

You can use CURL in place of file_get_contents()

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

回答by Amir

Some servers do not permit accessing through IP address in your request. You can use CURLto prevent this problem.

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