cURL可以工作,但PHP cURL无法连接互联网。

4

我会尝试使用PHP的cURL在RedHat Linux服务器上访问互联网位置来诊断问题。

cURL已安装并正常工作,且:

<?php var_dump(curl_version()); ?>

输出显示了所有正确的信息。问题在于我可以使用PHP通过cURL连接到本地主机,但无法连接到互联网(见下文)。

通常我会怀疑防火墙,但是我可以从命令行连接到互联网而没有任何问题。该主机也可以更新自己的软件包等。

我错过了什么?我的测试如下:

<?php 
    function http_head_curl($url,$timeout=30)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($ch);
        if ($res === false) {
            throw new RuntimeException("cURL exception: ".curl_errno($ch).": ".curl_error($ch));
        }
        return trim($res);
    }

    // Succeeds, displaying headers
    echo(http_head_curl('localhost'));

    // Fails:
    echo(http_head_curl('www.google.com'));
?>

3
+1 纯粹是因为“无法上网”。 - ArtOfCode
1个回答

1

您的服务器是否存在DNS解析问题?它始终能够解析 localhost,但可能无法解析 www.google.com。请尝试以下方法:

var_dump(dns_get_record('www.google.com'));

如果DNS未解析,则应获得以下内容:

If DNS if not resolving, you should get:

array(0) {}

如果DNS正常工作,您应该得到类似于以下内容的数组:
array(6) {
  [0]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(13) "74.125.201.99"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
  [1]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(14) "74.125.201.105"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
  [2]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(14) "74.125.201.104"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
  [3]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(14) "74.125.201.106"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
  [4]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(14) "74.125.201.103"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
  [5]=>
  array(5) {
    ["host"]=>
    string(14) "www.google.com"
    ["type"]=>
    string(1) "A"
    ["ip"]=>
    string(14) "74.125.201.147"
    ["class"]=>
    string(2) "IN"
    ["ttl"]=>
    int(375)
  }
}

1
已解决。感谢大家的帮助。我发现这个服务器需要使用代理。我们测试的用户帐户设置了代理,但Apache用户没有设置。编辑/etc/init.d/httpd init脚本即可解决。现在它会源一个包含环境变量的文件,一切都正常工作。 - wrk2bike
这个线程也很有帮助:http://serverfault.com/questions/379754/whats-preventing-the-apache-user-making-outbound-connections - wrk2bike
好消息。很高兴我能帮上忙,即使只是一点点。 :) - TunaMaxx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接