鍍金池/ 問答/PHP  Linux/ php中CURL報Could not resolve host錯誤

php中CURL報Could not resolve host錯誤

1、使用 file_get_contents() 函數(shù), 參數(shù)為域名地址時返回空,為ip地址時有數(shù)據(jù)。
2、linux中可以ping 通 域名
3、php-cli 執(zhí)行,可以訪問遠(yuǎn)程域名,并到得數(shù)據(jù)。
4、通過瀏覽器 即php-fpm模式 curl 和 file_get_contents 都不可以訪問遠(yuǎn)程域名。
5、在 /etc/hosts 中添加 220.181.112.244 www.baidu.com 后 php-fpm模式,就可以訪問到數(shù)據(jù)了。

代碼:

echo 1;
try {
    var_dump(file_get_contents('http://220.181.112.244/index.html'));
//    var_dump(file_get_contents('http://www.baidu.com'));
} catch (Exception $e) {
    print_r($e->getTrace());
}
echo 2;

1、參數(shù)為:http://www.baidu.com

clipboard.png

2、參數(shù)為:http://220.181.112.244/index....

clipboard.png

3、在服務(wù)器執(zhí)行腳本,兩種參數(shù)都有返回數(shù)據(jù)。

clipboard.png

這是file_get_contents() 方法請求的錯誤信息:

2018/05/26 22:16:03 [error] 24942#0: *46192 FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /data/com.9b/duolaixue_admin/test_print/test.php on line 13

php curl 請求的錯誤信息:
Could not resolve host: www.baidu.com; Name or service not known

回答
編輯回答
獨(dú)白

1、如果你是將你的上面代碼放到服務(wù)器運(yùn)行的話,百度的服務(wù)器可能會識別你USERAGENT為機(jī)器人robot,拒絕你的訪問

2、file_get_contents()某些時候是可行的,但是有些特殊情況也可以使用curl庫的函數(shù),為了防止對方識別你為robot,可以將服務(wù)器偽裝訪問的瀏覽器用戶是Mozilla/4.0,比如以下代碼

<?php 
$curl = curl_init(); 
//這里設(shè)置你的USERAGENT
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 

$xxx = curl_exec($curl); 

curl_close ($curl); 
echo $xxx; 
?>

curl相關(guān)的參數(shù)可見:http://php.net/manual/en/func...

補(bǔ)充:
關(guān)于你的問題,這段代碼我是運(yùn)行成功的

<?php
 $url = "http://www.baidu.com"; 
        $page = "/services/calculation"; 
        $headers = array( 
            "POST ".$page." HTTP/1.0", 
            "Content-type: text/xml;charset=\"utf-8\"", 
            "Accept: text/xml", 
            "Cache-Control: no-cache", 
            "Pragma: no-cache", 
            "SOAPAction: \"run\"", 
        ); 
       
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL,$url); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 

        $data = curl_exec($ch); 

        if (curl_errno($ch)) { 
            print "Error: " . curl_error($ch); 
        } else { 
            // Show me the result 
            var_dump($data); 
            curl_close($ch); 
        } 
?>

clipboard.png

2018年2月22日 21:19
編輯回答
賤人曾

如果是域名,就需要服務(wù)器端配置DNS??纯茨惴?wù)器上DNS能夠解析出域名對應(yīng)的ip。

2017年8月18日 05:00