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

How to resolve cURL Error (7): couldn't connect to host?

我使用cUrl(php)将项目代码以xml格式发送到Web服务。 我在localhost中得到正确的响应,但是在服务器执行该操作时,它显示

cURL Error (7): couldn't connect to host

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
"
;
    } else {
            echo"Data received
"
;
    }
    curl_close($ch);

    echo $data;
}

我将商品代码发送到理货单并从中获取详细信息。 我尝试同时使用php 4+和php5 +版本,没有任何解决方案。


CURL error code 7 (CURLE_COULDNT_CONNECT)

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

以下代码可在任何系统上运行:

1
2
3
4
$ch = curl_init("http://google.com");    // initialize curl handle
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
print($data);

如果看不到谷歌页面,则.. your URL is wrong或出现firewallrestriction问题。


当由于某种原因,某些防火墙或类似物阻止了curl请求时,将引发" CURL ERROR 7无法连接到权限被拒绝"错误。

当curl请求不具有标准端口时,您将面临此问题。

例如,如果您确实要卷曲到端口1234上的某个URL,则会遇到此问题,因为端口80的URL可以轻松为您提供结果。

最常见的错误是在CentOS和其他带有" SElinux"的操作系统上看到的。

您需要禁用或将" SElinux"更改为宽松

看看这个

CURL ERROR 7 Failed to connect to Permission denied

希望这可以帮助


就我而言,我有类似cURL Error (7): ... Operation Timed Out的东西。我正在使用我所工作公司的网络连接。我需要创建一些环境变量。下一个对我有用:

在Linux终端中:

1
2
$ export https_proxy=yourProxy:80
$ export http_proxy=yourProxy:80

在Windows中,我以Windows方式创建了(相同的)环境变量。

希望对您有所帮助!

问候!


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

1
2
curl_setopt($ch, CURLOPT_PROXY,"http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT,"80"); // your proxy port number

这是解决我的问题


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


在我的情况下,问题是由托管服务提供商引起的,因为我使用的是阻止发给其IP块的HTTP数据包,这些HTTP数据包源自其IP块。令人难以置信的可信!!!


如果未在远程设备上配置对https的curl调用,也可能导致此问题。在这些情况下,至少在远程上配置ssl之前,通过http调用可以解决此问题。


检查端口80和443是否被阻塞。或输入-IP graph.facebook.com并在etc / hosts文件中输入


如果您尝试同时使用多个HTTP请求命中相同的URL,也可以获得此信息。许多curl请求将无法连接,因此返回错误