PHP語言中php curl的幾種應(yīng)用方式
我們通過對(duì)PHP開發(fā)基礎(chǔ)入門這一專題的學(xué)習(xí)可以了解到,PHP語言的一些具體概念的實(shí)際應(yīng)用。今天我們向大家介紹的是在PHP中的php curl的幾種使用方式,希望對(duì)有需要的朋友有所幫助。
#t#1. php curl的默認(rèn)調(diào)用方法,get方式訪問url
- ....
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//設(shè)置http頭
- curl_setopt($ch, CURLOPT_ENCODING, "gzip" );
//設(shè)置為客戶端支持gzip壓縮- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 );
//設(shè)置連接等待時(shí)間- curl_setopt($ch, CURLOPT_URL, $url );
- curl_exec( $ch );
- if ($error = curl_error($ch) ) {
- //出錯(cuò)處理
- return -1;
- }
- fclose($fp);
- $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//獲取http返回值- if( $curl_code == 200 ) {
- //正常訪問url
- }
- //異常
- ....
2. 設(shè)置http header支持php curl訪問lighttpd服務(wù)器
- $header[]= 'Expect:';
3. 設(shè)置curl,只獲取http header,不獲取body:
- curl_setopt($ch, CURLOPT_HEADER, 1);
- curl_setopt($ch, CURLOPT_NOBODY, 1);
或者只獲取body:
- curl_setopt($ch, CURLOPT_HEADER, 0);
// make sure we get the body- curl_setopt($ch, CURLOPT_NOBODY, 0);
4. 訪問虛擬主機(jī),需設(shè)置Host
- $header[]= 'Host: '.$host;
5. 使用post, put, delete等REStful方式訪問url
- post:
- curl_setopt($ch, CURLOPT_POST, 1 );
- put, delete:
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
//或者PUT,需要服務(wù)器支持這些方法。
6. php curl保存下載內(nèi)容為文件
- curl_setopt($ch, CURLOPT_FILE, $fp);