1. 程式人生 > >php中curl、fsocket、file_get_content三個函式的使用比較

php中curl、fsocket、file_get_content三個函式的使用比較

php中curl和file_get_content的一些比較

主要區別:

學習才發現,curl支援很多協議,有FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE以及LDAP,也就是說,它能做到很多file_get_content做不到的事情。curl在php可以實現遠端獲取和採集內容;實現PHP網頁版的FTP上傳下載;實現模擬登陸;實現介面對接(API),資料傳輸;實現模擬Cookie;下載檔案斷點續傳等等,功能十分強大。

開啟curl:

因為PHP預設是不支援curl功能的,因此如果要用curl的話,首先需要在php.ini中開啟該功能,即去掉 ;extension= php_curl.dll 前面的分號,然後儲存後重啟apache/iis就好了。

基本語法:

$my_curl = curl_init();    //初始化一個curl物件
curl_setopt($my_curl, CURLOPT_URL, "//www.jb51.net");    //設定你需要抓取的URL
curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1);    //設定是將結果儲存到字串中還是輸出到螢幕上,1表示將結果儲存到字串
$str = curl_exec($curl);    //執行請求
echo $str;    //輸出抓取的結果
curl_close($curl);    //關閉url請求

一個簡單的curl使用方法:

function curl_file_get_contents($durl){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $durl);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
    curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $r = curl_exec($ch);
    curl_close($ch);
    return $r;
}

別人測試file_get_content和curl的獲取資料的時間差

file_get_contents抓取google.com需用秒數:

2.31319094
2.30374217
2.21512604
3.30553889
2.30124092

curl使用的時間:

0.68719101
0.64675593
0.64326
0.81983113
0.63956594

差距很大?呵呵,從我使用的經驗來說,這兩個工具不只是速度有差異,穩定性也相差很大。

建議對網路資料抓取穩定性要求比較高的朋友使用上面的 curl_file_get_contents函式,不但穩定速度快,還能假冒瀏覽器欺騙目標地址哦!

方法1: 用file_get_contents 以get方式獲取內容

<?php
$url='http://www.domain.com/';
$html = file_get_contents($url);
echo $html;
?>

方法2: 用fopen開啟url, 以get方式獲取內容

<?php
$fp = fopen($url, 'r');
stream_get_meta_data($fp);
while(!feof($fp)) {
    $result .= fgets($fp, 1024);
}
echo "url body: $result";
fclose($fp);
?>

方法3:用file_get_contents函式,以post方式獲取url

<?php
$data = array ('foo' => 'bar');
$data = http_build_query($data);
$opts = array (
    'http' => array (
    'method' => 'POST',
    'header'=> "Content-type: application/x-www-form-urlencodedrn" .
    "Content-Length: " . strlen($data) . "rn",
    'content' => $data
)
);
$context = stream_context_create($opts);
$html = file_get_contents('http://localhost/e/admin/test.html', false, $context);
echo $html;
?>

方法4:用fsockopen函式開啟url,以get方式獲取完整的資料,包括header和body

<?php
function get_url ($url,$cookie=false)
{
    $url = parse_url($url);
    $query = $url[path]."?".$url[query];
    //echo "Query:".$query;
    $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
    if (!$fp) {
        return false;
    } else {
        $request = "GET $query HTTP/1.1rn";
        $request .= "Host: $url[host]rn";
        $request .= "Connection: Closern";
        if($cookie) $request.="Cookie: $cookien";
            $request.="rn";
        fwrite($fp,$request);
        while()) {
            $result .= @fgets($fp, 1024);
        }
        fclose($fp);
        return $result;
    }
}
//獲取url的html部分,去掉header
function GetUrlHTML($url,$cookie=false)
{
    $rowdata = get_url($url,$cookie);
    if($rowdata)
    {
        $body= stristr($rowdata,"rnrn");
        $body=substr($body,4,strlen($body));
        return $body;
    }
    return false;
}
?>

方法5:用fsockopen函式開啟url,以POST方式獲取完整的資料,包括header和body

<?php
function HTTP_Post($URL,$data,$cookie, $referrer="")
{
    // parsing the given URL
    $URL_Info=parse_url($URL);
    // Building referrer
    if($referrer=="") // if not given use this script as referrer
        $referrer="111″;

    // making string from $data
    foreach($data as $key=>$value)
        $values[]="$key=".urlencode($value);
        $data_string=implode("&",$values);
        // Find out which port is needed – if not given use standard (=80)
    if(!isset($URL_Info["port"]))
    $URL_Info["port"]=80;
    // building POST-request:
    $request.="POST ".$URL_Info["path"]." HTTP/1.1n";
    $request.="Host: ".$URL_Info["host"]."n";
    $request.="Referer: $referern";
    $request.="Content-type: application/x-www-form-urlencodedn";
    $request.="Content-length: ".strlen($data_string)."n";
    $request.="Connection: closen";
    $request.="Cookie: $cookien";
    $request.="n";
    $request.=$data_string."n";
    $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
    fputs($fp, $request);
    while(!feof($fp)) {
        $result .= fgets($fp, 1024);
    }
    fclose($fp);
    return $result;
}
?>

方法6:使用curl庫,使用curl庫之前,可能需要檢視一下php.ini是否已經打開了curl擴充套件

<?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, CURLOPT_URL, 'http://www.domain.com/');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>

原文地址:https://www.jb51.net/article/49949.htm