如何解决cURL错误(7):无法连接到主机?

Raj*_*Raj 56 php xml curl

我使用cUrl(php)将项目代码以xml格式发送到Web服务.我在localhost中得到了正确的响应,但是什么时候服务器显示它

cURL错误(7):无法连接到主机

这是我的代码:

function xml_post($post_xml, $url)
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    $ch = curl_init();    // initialize curl handle
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);          
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 50); 
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); 
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
//  curl_setopt($ch, CURLOPT_PORT, $port);          

    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    if ($curl_errno > 0) {
            echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
            echo "Data received\n";
    }
    curl_close($ch);

    echo $data;
}
Run Code Online (Sandbox Code Playgroud)

我将商品代码发送到计数器并从中获取详细信息.我尝试使用php 4+和php5 +两个版本,没有任何解决方案.

Bab*_*aba 44

CURL错误代码7(CURLE_COULDNT_CONNECT)

非常明确......这意味着 Failed to connect() to host or proxy.

以下代码适用于任何系统:

$ch = curl_init("http://google.com");    // initialize curl handle
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
print($data);
Run Code Online (Sandbox Code Playgroud)

如果你看不到谷歌页面.. your URL is wrong或者你有一些firewallrestriction问题.

  • @Baba你说:`如果你看不到google页面那么..你的网址错了或你有一些防火墙或限制问题.可能存在哪些限制? (3认同)
  • @hpaknia 谢谢,有时我们看不到明显的...补充您的回答,在 Linux 系统中,请记住检查有关您的 Web 服务对正在执行的文件的访问的 ACL 和 SELinux 权限。 (2认同)

小智 20

"CURL错误7无法连接到权限被拒绝"错误是由于任何原因导致curl请求被某些防火墙或类似事件阻止.

当卷曲请求不是标准端口时,您将面临此问题.

例如,如果你卷曲到端口1234上的某个URL,你将面临这个问题,因为带端口80的URL可以轻松地为你提供结果.

最常见的是这个错误已在CentOS和任何其他具有'SElinux'的操作系统上看到.

您需要禁用或更改'SElinux'以允许

看看这一个

http://www.akashif.co.uk/php/curl-error-7-failed-to-connect-to-permission-denied

希望这可以帮助

  • 禁用SELinux是过度的,会对其他区域的安全性产生负面影响.您可以通过从终端更改该特定选项来明确允许除已知端口之外的端口:setsebool -P httpd_can_network_connect on (6认同)
  • 但是mac系统怎么样 (2认同)

Ima*_*shi 13

如果您尝试了所有方法但都失败了,请尝试以下命令:

setsebool -P httpd_can_network_connect on
Run Code Online (Sandbox Code Playgroud)

  • 在服务器迁移过程中,这让我在一个非常旧的 PHP 脚本上花了几个小时追查错误的错误后救了我一命。我的日志中唯一的错误是“[7]”,我没有意识到它来自于curl。我偶然发现了这个答案,它已经恢复并运行了! (2认同)

小智 5

在 PHP 中,如果您的网络在代理下。您应该设置代理 URL 和端口

curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number
Run Code Online (Sandbox Code Playgroud)

这是解决我的问题


Moh*_*gam 2

您可以通过浏览器或 PHP 脚本访问该 URL 吗?显示的错误是您无法连接。所以首先确认该URL可以访问。

  • 是的。从本地主机我可以访问它。我在浏览器中 ping 它,它 ping 通。 (3认同)