1、 一(yī)個抓取網頁的(de)簡單案例:
// 創建一(yī)個新cURL資源 $ch = curl_init(); // 設置URL和(hé)相應的(de)選項 curl_setopt($ch, CURLOPT_URL, "http://www.baidu.com/"); curl_setopt($ch, CURLOPT_HEADER, false); // 抓取URL并把它傳遞給浏覽器 curl_exec($ch); //關閉cURL資源,并且釋放系統資源 curl_close($ch);
2、POST數據案例:
// 創建一(yī)個新cURL資源 $ch = curl_init(); $data = 'phone='. urlencode($phone); // 設置URL和(hé)相應的(de)選項 curl_setopt($ch, CURLOPT_URL, "http://www.post.com/"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 抓取URL并把它傳遞給浏覽器 curl_exec($ch); //關閉cURL資源,并且釋放系統資源 curl_close($ch);
3、關于SSL和(hé)Cookie
關于SSL也就是HTTPS協議,你隻需要把CURLOPT_URL連接中的(de)http://變成https://就可(kě)以了。當然,還有一(yī)個參數叫CURLOPT_SSL_VERIFYHOST可(kě)以設置為(wèi)驗證站點。
關于Cookie,你需要了解下面三個參數:
CURLOPT_COOKIE,在當面的(de)會話中設置一(yī)個cookie
CURLOPT_COOKIEJAR,當會話結束的(de)時候保存一(yī)個Cookie
CURLOPT_COOKIEFILE,Cookie的(de)文件。
PS:新浪微博登陸API部分截取
/** * Make an HTTP request * * @return string API results * @ignore */ function http($url, $method, $postfields = NULL, $headers = array()) { $this->http_info = array(); $ci = curl_init(); /* Curl settings */ curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);//讓cURL自(zì)己判斷使用哪個版本 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);//在HTTP請求中包含一(yī)個"User-Agent: "頭的(de)字符串。 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);//在發起連接前等待的(de)時間,如(rú)果設置為(wèi)0,則無限等待 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);//設置cURL允許執行的(de)最長(cháng)秒數 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);//返回原生的(de)(Raw)輸出 curl_setopt($ci, CURLOPT_ENCODING, "");//HTTP請求頭中"Accept-Encoding: "的(de)值。支持的(de)編碼有"identity","deflate"和(hé)"gzip"。如(rú)果為(wèi)空字符串"",請求頭會發送所有支持的(de)編碼類型。 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);//禁用後cURL将終止從服務端進行驗證 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));//第一(yī)個是cURL的(de)資源句柄,第二個是輸出的(de)header數據 curl_setopt($ci, CURLOPT_HEADER, FALSE);//啓用時會将頭文件的(de)信息作為(wèi)數據流輸出 switch ($method) { case 'POST': curl_setopt($ci, CURLOPT_POST, TRUE); if (!empty($postfields)) { curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields); $this->postdata = $postfields; } break; case 'DELETE': curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE'); if (!empty($postfields)) { $url = "{$url}?{$postfields}"; } } if ( isset($this->access_token) && $this->access_token ) $headers[] = "Authorization: OAuth2 ".$this->access_token; $headers[] = "API-RemoteIP: " . $_SERVER['REMOTE_ADDR']; curl_setopt($ci, CURLOPT_URL, $url ); curl_setopt($ci, CURLOPT_HTTPHEADER, $headers ); curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE ); $response = curl_exec($ci); $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE); $this->http_info = array_merge($this->http_info, curl_getinfo($ci)); $this->url = $url; if ($this->debug) { echo "=====post data======\r\n"; var_dump($postfields); echo '=====info====='."\r\n"; print_r( curl_getinfo($ci) ); echo '=====$response====='."\r\n"; print_r( $response ); } curl_close ($ci); return $response; }