php中 curl, fsockopen ,file_get_contents 三個函數 比較

趙永斌:
有些時候用file_get_contents()調用外部文件,容易超時報錯。換成curl後就能夠.具體緣由不清楚
curl 效率比file_get_contents()和fsockopen()高一些,緣由是CURL會自動對DNS信息進行緩存(亮點啊 有我待親測)

範佳鵬:
file_get_contents curl fsockopen
在當前所請求環境下選擇性操做,沒有一律而論:
具咱們公司開發KBI應用來看:
剛開始採用:file_get_contents
後來採用:fsockopen
最後到至今採用:curl

(遠程)我我的理解到的表述以下(不對請指出,不到位請補充)
file_get_contents 須要php.ini裏開啓allow_url_fopen,請求http時,使用的是http_fopen_wrapper,不會keeplive.curl是能夠的。
file_get_contents()單個執行效率高,返回沒有頭的信息。
這個是讀取通常文件的時候並無什麼問題,可是在讀取遠程問題的時候就會出現問題。
若是是要打一個持續鏈接,屢次請求多個頁面。那麼file_get_contents和fopen就會出問題。
取得的內容也可能會不對。因此作一些相似採集工做的時候,確定就有問題了。
sock較底層,配置麻煩,不易操做。 返回完整信息。

潘少寧-騰訊:
file_get_contents 雖然能夠得到某URL的內容,但不能post  get啊。
curl 則能夠post和get啊。還能夠得到head信息
而socket則更底層。能夠設置基於UDP或是TCP協議去交互
file_get_contents 和 curl 能幹的,socket都能幹。
socket能幹的,curl 就不必定能幹了
file_get_contents  更多的時候 只是去拉取數據。效率比較高  也比較簡單。

趙的狀況這個我也遇到過,我經過CURL設置host 就OK了。  這和網絡環境有關係 php

<?php

/**
 * Socket版本 
 * 使用方法: 
 * $post_string = "app=socket&amp;version=beta"; 
 * request_by_socket('facebook.cn','/restServer.php',$post_string); 
 */
function request_by_socket($remote_server, $remote_path, $post_string, $port = 80, $timeout = 30)
{
    $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
    if (!$socket)
        die("$errstr($errno)");
    fwrite($socket, "POST $remote_path HTTP/1.0");
    fwrite($socket, "User-Agent: Socket Example");
    fwrite($socket, "HOST: $remote_server");
    fwrite($socket, "Content-type: application/x-www-form-urlencoded");
    fwrite($socket, "Content-length: " . strlen($post_string) + 8);
    fwrite($socket, "Accept:*/*");
    fwrite($socket, "");
    fwrite($socket, "mypost=$post_string");
    fwrite($socket, "");
    $header = "";
    while ($str = trim(fgets($socket, 4096)))
    {
        $header .= $str;
    }

    $data = "";
    while (!feof($socket))
    {
        $data .= fgets($socket, 4096);
    }
    return $data;
}

?>
<?php

/**
 * Curl版本   
 * 使用方法:   
 * $post_string = "app=request&version=beta";   
 * request_by_curl('http://facebook.cn/restServer.php',$post_string);   
 */
function request_by_curl($remote_server, $post_string)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $remote_server);
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'mypost=' . $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Jimmy's CURL Example beta");
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

?>
相關文章
相關標籤/搜索