我們通過對1. php curl的默認調用方法,get方式訪問url
- ....
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);//設置http頭
- curl_setopt($ch, CURLOPT_ENCODING, "gzip" );
//設置為客戶端支持gzip壓縮- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 );
//設置連接等待時間- curl_setopt($ch, CURLOPT_URL, $url );
- curl_exec( $ch );
- if ($error = curl_error($ch) ) {
- //出錯處理
- return -1;
- }
- fclose($fp);
- $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//獲取http返回值- if( $curl_code == 200 ) {
- //正常訪問url
- }
- //異常
- ....
2. 設置http header支持php curl訪問lighttpd服務器
- $header[]= 'Expect:';
3. 設置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. 訪問虛擬主機,需設置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,需要服務器支持這些方法。
6. php curl保存下載內容為文件
- curl_setopt($ch, CURLOPT_FILE, $fp);