php中使用Curl、socket、file_get_contents三種方法POST提交數據


抓取遠程內容,之前一直都在用file_get_content函數,其實早就知道有curl這么一個好東西的存在,但是看了一眼后感覺使用頗有些復雜,沒有file_get_content那么簡單,再就是需求也不大,所以沒有學習使用curl。

直到最近,要做一個網頁小偷程序的時候才發現file_get_content已經完全不能滿足需求了。我覺得,在讀取遠程內容的時候,file_get_content除了使用比curl便捷以外,其他都沒有curl好。

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一些基本的使用后,才發現其實並不難,只不過記住里面一些設置參數,難弄一點,但是我們記住幾個常用的就可以了。

開啟curl:

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

基本語法:

1 $my_curl = curl_init();    //初始化一個curl對象
2 curl_setopt($my_curl, CURLOPT_URL, "http://www.jb51.net");    //設置你需要抓取的URL
3 curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1);    //設置是將結果保存到字符串中還是輸出到屏幕上,1表示將結果保存到字符串
4 $str = curl_exec($curl);    //執行請求
5 echo $str;    //輸出抓取的結果
6 curl_close($curl);    //關閉url請求

最近需要獲取別人網站上的音樂數據。用了file_get_contents函數,但是總是會遇到獲取失敗的問題,盡管按照手冊中的例子設置了超時,可多數時候不會奏效:

1 $config['context'] = stream_context_create(array('http' => array('method' => "GET",
2 'timeout' => 5//這個超時時間不穩定,經常不奏效
3 )
4 ));

這時候,看一下服務器的連接池,會發現一堆類似的錯誤,讓我頭疼萬分:

file_get_contents(http://***): failed to open stream…

現在改用了curl庫,寫了一個函數替換:

 1 function curl_file_get_contents($durl){
 2 $ch = curl_init();
 3 curl_setopt($ch, CURLOPT_URL, $durl);
 4 curl_setopt($ch, CURLOPT_TIMEOUT, 5);
 5 curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
 6 curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
 7 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 8 $r = curl_exec($ch);
 9 curl_close($ch);
10 return $r;
11 }

如此,除了真正的網絡問題外,沒再出現任何問題。

這是別人做過的關於curl和file_get_contents的測試:

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方式獲取內容

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

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

1 <?php
2 $fp = fopen($url, 'r');
3 stream_get_meta_data($fp);
4 while(!feof($fp)) {
5 $result .= fgets($fp, 1024);
6 }
7 echo "url body: $result";
8 fclose($fp);
9 ?>

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

 1 <?php
 2 $data = array ('foo' => 'bar');
 3 $data = http_build_query($data);
 4 $opts = array (
 5 'http' => array (
 6 'method' => 'POST',
 7 'header'=> "Content-type: application/x-www-form-urlencodedrn" .
 8 "Content-Length: " . strlen($data) . "rn",
 9 'content' => $data
10 )
11 );
12 $context = stream_context_create($opts);
13 $html = file_get_contents('http://localhost/e/admin/test.html', false, $context);
14 echo $html;
15 ?>

方法4:用fsockopen函數打開url,以get方式獲取完整的數據,包括header和body

 1 <?php
 2 function get_url ($url,$cookie=false)
 3 {
 4 $url = parse_url($url);
 5 $query = $url[path]."?".$url[query];
 6 echo "Query:".$query;
 7 $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
 8 if (!$fp) {
 9 return false;
10 } else {
11 $request = "GET $query HTTP/1.1rn";
12 $request .= "Host: $url[host]rn";
13 $request .= "Connection: Closern";
14 if($cookie) $request.="Cookie: $cookien";
15 $request.="rn";
16 fwrite($fp,$request);
17 while()) {
18 $result .= @fgets($fp, 1024);
19 }
20 fclose($fp);
21 return $result;
22 }
23 }
24 //獲取url的html部分,去掉header
25 function GetUrlHTML($url,$cookie=false)
26 {
27 $rowdata = get_url($url,$cookie);
28 if($rowdata)
29 {
30 $body= stristr($rowdata,"rnrn");
31 $body=substr($body,4,strlen($body));
32 return $body;
33 }
34 return false;
35 }
36 ?>

方法5:用fsockopen函數打開url,以POST方式獲取完整的數據,包括header和body

 1 <?php
 2 function HTTP_Post($URL,$data,$cookie, $referrer="")
 3 {
 4 // parsing the given URL
 5 $URL_Info=parse_url($URL);
 6 // Building referrer
 7 if($referrer=="") // if not given use this script as referrer
 8 $referrer="111″;
 9 // making string from $data
10 foreach($data as $key=>$value)
11 $values[]="$key=".urlencode($value);
12 $data_string=implode("&",$values);
13 // Find out which port is needed – if not given use standard (=80)
14 if(!isset($URL_Info["port"]))
15 $URL_Info["port"]=80;
16 // building POST-request:
17 $request.="POST ".$URL_Info["path"]." HTTP/1.1n";
18 $request.="Host: ".$URL_Info["host"]."n";
19 $request.="Referer: $referern";
20 $request.="Content-type: application/x-www-form-urlencodedn";
21 $request.="Content-length: ".strlen($data_string)."n";
22 $request.="Connection: closen";
23 $request.="Cookie: $cookien";
24 $request.="n";
25 $request.=$data_string."n";
26 $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
27 fputs($fp, $request);
28 while(!feof($fp)) {
29 $result .= fgets($fp, 1024);
30 }
31 fclose($fp);
32 return $result;
33 }
34 ?>

方法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;
?>

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了。 這和網絡環境有關系

 1 <?php 
 2 /** 
 3 * Socket版本 
 4 * 使用方法: 
 5 * $post_string = "app=socket&version=beta"; 
 6 * request_by_socket('jb51.net','/restServer.php',$post_string); 
 7 */ 
 8 function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30){ 
 9 $socket = fsockopen($remote_server,$port,$errno,$errstr,$timeout); 
10 if (!$socket) die("$errstr($errno)"); 
11 fwrite($socket,"POST $remote_path HTTP/1.0"); 
12 fwrite($socket,"User-Agent: Socket Example"); 
13 fwrite($socket,"HOST: $remote_server"); 
14 fwrite($socket,"Content-type: application/x-www-form-urlencoded"); 
15 fwrite($socket,"Content-length: ".strlen($post_string)+8.""); 
16 fwrite($socket,"Accept:*/*"); 
17 fwrite($socket,""); 
18 fwrite($socket,"mypost=$post_string"); 
19 fwrite($socket,""); 
20 $header = ""; 
21 while ($str = trim(fgets($socket,4096))) { 
22 $header.=$str; 
23 } 
24 $data = ""; 
25 while (!feof($socket)) { 
26 $data .= fgets($socket,4096); 
27 } 
28 return $data; 
29 } 
30 /** 
31 * Curl版本 
32 * 使用方法: 
33 * $post_string = "app=request&version=beta"; 
34 * request_by_curl('http://jb51.net/restServer.php',$post_string); 
35 */ 
36 function request_by_curl($remote_server,$post_string){ 
37 $ch = curl_init(); 
38 curl_setopt($ch,CURLOPT_URL,$remote_server); 
39 curl_setopt($ch,CURLOPT_POSTFIELDS,'mypost='.$post_string); 
40 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); 
41 curl_setopt($ch,CURLOPT_USERAGENT,"Jimmy's CURL Example beta"); 
42 $data = curl_exec($ch); 
43 curl_close($ch); 
44 return $data; 
45 } 
46 /** 
47 * 其它版本 
48 * 使用方法: 
49 * $post_string = "app=request&version=beta"; 
50 * request_by_other('http://jb51.net/restServer.php',$post_string); 
51 */ 
52 function request_by_other($remote_server,$post_string){ 
53 $context = array( 
54 'http'=>array( 
55 'method'=>'POST', 
56 'header'=>'Content-type: application/x-www-form-urlencoded'."". 
57 'User-Agent : Jimmy's POST Example beta'."". 
58 'Content-length: '.strlen($post_string)+8, 
59 'content'=>'mypost='.$post_string) 
60 ); 
61 $stream_context = stream_context_create($context); 
62 $data = file_get_contents($remote_server,FALSE,$stream_context); 
63 return $data; 
64 } 
65 ?> 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM