php中使用Curl、socket、file_get_contents三種方法POST提交數(shù)據(jù)
抓取遠(yuǎn)程內(nèi)容,之前一直都在用file_get_content函數(shù),其實(shí)早就知道有curl這么一個(gè)好東西的存在,但是看了一眼后感覺使用頗有些復(fù)雜,沒有file_get_content那么簡(jiǎn)單,再就是需求也不大,所以沒有學(xué)習(xí)使用curl。
直到最近,要做一個(gè)網(wǎng)頁(yè)小偷程序的時(shí)候才發(fā)現(xiàn)file_get_content已經(jīng)完全不能滿足需求了。我覺得,在讀取遠(yuǎn)程內(nèi)容的時(shí)候,file_get_content除了使用比curl便捷以外,其他都沒有curl好。
php中curl和file_get_content的一些比較
主要區(qū)別:
學(xué)習(xí)才發(fā)現(xiàn),curl支持很多協(xié)議,有FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE以及LDAP,也就是說,它能做到很多file_get_content做不到的事情。curl在php可以實(shí)現(xiàn)遠(yuǎn)程獲取和采集內(nèi)容;實(shí)現(xiàn)PHP網(wǎng)頁(yè)版的FTP上傳下載;實(shí)現(xiàn)模擬登陸;實(shí)現(xiàn)接口對(duì)接(API),數(shù)據(jù)傳輸;實(shí)現(xiàn)模擬Cookie;下載文件斷點(diǎn)續(xù)傳等等,功能十分強(qiáng)大。
了解curl一些基本的使用后,才發(fā)現(xiàn)其實(shí)并不難,只不過記住里面一些設(shè)置參數(shù),難弄一點(diǎn),但是我們記住幾個(gè)常用的就可以了。
開啟curl:
因?yàn)镻HP默認(rèn)是不支持curl功能的,因此如果要用curl的話,首先需要在php.ini中開啟該功能,即去掉 ;extension= php_curl.dll 前面的分號(hào),然后保存后重啟apache/iis就好了。
基本語(yǔ)法:
$my_curl = curl_init(); //初始化一個(gè)curl對(duì)象
curl_setopt($my_curl, CURLOPT_URL, "http://www.dhdzp.com"); //設(shè)置你需要抓取的URL
curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1); //設(shè)置是將結(jié)果保存到字符串中還是輸出到屏幕上,1表示將結(jié)果保存到字符串
$str = curl_exec($curl); //執(zhí)行請(qǐng)求
echo $str; //輸出抓取的結(jié)果
curl_close($curl); //關(guān)閉url請(qǐng)求
最近需要獲取別人網(wǎng)站上的音樂數(shù)據(jù)。用了file_get_contents函數(shù),但是總是會(huì)遇到獲取失敗的問題,盡管按照手冊(cè)中的例子設(shè)置了超時(shí),可多數(shù)時(shí)候不會(huì)奏效:
$config['context'] = stream_context_create(array('http' => array('method' => "GET",
'timeout' => 5//這個(gè)超時(shí)時(shí)間不穩(wěn)定,經(jīng)常不奏效
)
));
這時(shí)候,看一下服務(wù)器的連接池,會(huì)發(fā)現(xiàn)一堆類似的錯(cuò)誤,讓我頭疼萬分:
file_get_contents(http://***): failed to open stream…
現(xiàn)在改用了curl庫(kù),寫了一個(gè)函數(shù)替換:
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;
}
如此,除了真正的網(wǎng)絡(luò)問題外,沒再出現(xiàn)任何問題。
這是別人做過的關(guān)于curl和file_get_contents的測(cè)試:
file_get_contents抓取google.com需用秒數(shù):
2.31319094
2.30374217
2.21512604
3.30553889
2.30124092
curl使用的時(shí)間:
0.68719101
0.64675593
0.64326
0.81983113
0.63956594
差距很大?呵呵,從我使用的經(jīng)驗(yàn)來說,這兩個(gè)工具不只是速度有差異,穩(wěn)定性也相差很大。
建議對(duì)網(wǎng)絡(luò)數(shù)據(jù)抓取穩(wěn)定性要求比較高的朋友使用上面的 curl_file_get_contents函數(shù),不但穩(wěn)定速度快,還能假冒瀏覽器欺騙目標(biāo)地址哦!
方法1: 用file_get_contents 以get方式獲取內(nèi)容
<?php
$url='http://www.domain.com/';
$html = file_get_contents($url);
echo $html;
?>
方法2: 用fopen打開url, 以get方式獲取內(nèi)容
<?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函數(shù),以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函數(shù)打開url,以get方式獲取完整的數(shù)據(jù),包括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函數(shù)打開url,以POST方式獲取完整的數(shù)據(jù),包括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庫(kù),使用curl庫(kù)之前,可能需要查看一下php.ini是否已經(jīng)打開了curl擴(kuò)展
<?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 三個(gè)函數(shù) 都可以實(shí)現(xiàn)采集模擬發(fā)言 。三者有什么區(qū)別,或者講究么
趙永斌:
有些時(shí)候用file_get_contents()調(diào)用外部文件,容易超時(shí)報(bào)錯(cuò)。換成curl后就可以.具體原因不清楚
curl 效率比file_get_contents()和fsockopen()高一些,原因是CURL會(huì)自動(dòng)對(duì)DNS信息進(jìn)行緩存(亮點(diǎn)啊有我待親測(cè))
范佳鵬:
file_get_contents curl fsockopen
在當(dāng)前所請(qǐng)求環(huán)境下選擇性操作,沒有一概而論:
具我們公司開發(fā)KBI應(yīng)用來看:
剛開始采用:file_get_contents
后來采用:fsockopen
最后到至今采用:curl
(遠(yuǎn)程)我個(gè)人理解到的表述如下(不對(duì)請(qǐng)指出,不到位請(qǐng)補(bǔ)充)
file_get_contents 需要php.ini里開啟allow_url_fopen,請(qǐng)求http時(shí),使用的是http_fopen_wrapper,不會(huì)keeplive.curl是可以的。
file_get_contents()單個(gè)執(zhí)行效率高,返回沒有頭的信息。
這個(gè)是讀取一般文件的時(shí)候并沒有什么問題,但是在讀取遠(yuǎn)程問題的時(shí)候就會(huì)出現(xiàn)問題。
如果是要打一個(gè)持續(xù)連接,多次請(qǐng)求多個(gè)頁(yè)面。那么file_get_contents和fopen就會(huì)出問題。
取得的內(nèi)容也可能會(huì)不對(duì)。所以做一些類似采集工作的時(shí)候,肯定就有問題了。
sock較底層,配置麻煩,不易操作。 返回完整信息。
潘少寧-騰訊:
file_get_contents 雖然可以獲得某URL的內(nèi)容,但不能post get啊。
curl 則可以post和get啊。還可以獲得head信息
而socket則更底層。可以設(shè)置基于UDP或是TCP協(xié)議去交互
file_get_contents 和 curl 能干的,socket都能干。
socket能干的,curl 就不一定能干了
file_get_contents 更多的時(shí)候 只是去拉取數(shù)據(jù)。效率比較高 也比較簡(jiǎn)單。
趙的情況這個(gè)我也遇到過,我通過CURL設(shè)置host 就OK了。 這和網(wǎng)絡(luò)環(huán)境有關(guān)系
<?php
/**
* Socket版本
* 使用方法:
* $post_string = "app=socket&version=beta";
* request_by_socket('jb51.net','/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;
}
/**
* Curl版本
* 使用方法:
* $post_string = "app=request&version=beta";
* request_by_curl('http://jb51.net/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;
}
/**
* 其它版本
* 使用方法:
* $post_string = "app=request&version=beta";
* request_by_other('http://jb51.net/restServer.php',$post_string);
*/
function request_by_other($remote_server,$post_string){
$context = array(
'http'=>array(
'method'=>'POST',
'header'=>'Content-type: application/x-www-form-urlencoded'."".
'User-Agent : Jimmy's POST Example beta'."".
'Content-length: '.strlen($post_string)+8,
'content'=>'mypost='.$post_string)
);
$stream_context = stream_context_create($context);
$data = file_get_contents($remote_server,FALSE,$stream_context);
return $data;
}
?>
- PHP中使用cURL實(shí)現(xiàn)Get和Post請(qǐng)求的方法
- php的curl實(shí)現(xiàn)get和post的代碼
- PHP中的使用curl發(fā)送請(qǐng)求(GET請(qǐng)求和POST請(qǐng)求)
- PHP的curl實(shí)現(xiàn)get,post和cookie(實(shí)例介紹)
- 詳解php用curl調(diào)用接口方法,get和post兩種方式
- php使用CURL模擬GET與POST向微信接口提交及獲取數(shù)據(jù)的方法
- PHP CURL模擬GET及POST函數(shù)代碼
- PHP如何使用cURL實(shí)現(xiàn)Get和Post請(qǐng)求
- PHP中使用CURL發(fā)送get/post請(qǐng)求上傳圖片批處理功能
- php curl發(fā)起get與post網(wǎng)絡(luò)請(qǐng)求案例詳解
- PHP curl get post 請(qǐng)求的封裝函數(shù)示例【get、post、put、delete等請(qǐng)求類型】
相關(guān)文章
php常用Output和ptions/Info函數(shù)集介紹
本篇文章是對(duì)php中常用Output和ptions/Info函數(shù)集進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
PHP __autoload函數(shù)(自動(dòng)載入類文件)的使用方法
在使用PHP的OO模式開發(fā)系統(tǒng)時(shí),通常大家習(xí)慣上將每個(gè)類的實(shí)現(xiàn)都存放在一個(gè)單獨(dú)的文件里,這樣會(huì)很容易實(shí)現(xiàn)對(duì)類進(jìn)行復(fù)用,同時(shí)將來維護(hù)時(shí)也很便利2012-02-02
PHP實(shí)現(xiàn)域名whois查詢的代碼(數(shù)據(jù)源萬網(wǎng)、新網(wǎng))
對(duì)于whois查詢,數(shù)據(jù)來自萬網(wǎng)、新網(wǎng),數(shù)據(jù)也比較權(quán)威,需要的朋友可以參考下。2010-02-02
PHP fgetcsv 定義和用法(附windows與linux下兼容問題)
PHP fgetcsv() 函數(shù)從文件指針中讀入一行并解析 CSV 字段。與PHP fgets() 類似,不同的是 PHP fgetcsv() 解析讀入的行并找出 CSV 格式的字段,然后返回一個(gè)包含這些字段的數(shù)組2012-05-05
通過緩存數(shù)據(jù)庫(kù)結(jié)果提高PHP性能的原理介紹
眾所周知,緩存數(shù)據(jù)庫(kù)查詢的結(jié)果可以顯著縮短腳本執(zhí)行時(shí)間,并最大限度地減少數(shù)據(jù)庫(kù)服務(wù)器上的負(fù)載。如果要處理的數(shù)據(jù)基本上是靜態(tài)的,則該技術(shù)將非常有效。這是因?yàn)閷?duì)遠(yuǎn)程數(shù)據(jù)庫(kù)的許多數(shù)據(jù)請(qǐng)求最終可以從本地緩存得到滿足,從而不必連接到數(shù)據(jù)庫(kù)、執(zhí)行查詢以及獲取結(jié)果2012-09-09
php學(xué)習(xí)之?dāng)?shù)據(jù)類型之間的轉(zhuǎn)換代碼
php學(xué)習(xí)之?dāng)?shù)據(jù)類型之間的轉(zhuǎn)換代碼,主要解決php中一些數(shù)據(jù)類型之間的相互轉(zhuǎn)換。2011-05-05

