PHP的curl功能十分強大,簡單點說,就是一個PHP實現瀏覽器的基礎。php
最經常使用的可能就是抓取遠程數據或者向遠程POST數據。可是在這個過程當中,調試時,可能會有查看header的必要。html
以下:瀏覽器
echo get('http://www.baidu.com');exit; function get($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HTTPGET, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //TRUE 將curl_exec()獲取的信息以字符串返回,而不是直接輸出。 $header = ['User-Agent: php test']; //設置一個你的瀏覽器agent的header curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_HEADER, 1); //返回response頭部信息 curl_setopt($ch, CURLINFO_HEADER_OUT, true); //TRUE 時追蹤句柄的請求字符串,從 PHP 5.1.3 開始可用。這個很關鍵,就是容許你查看請求header curl_setopt($ch, CURLOPT_URL, $url); $result = curl_exec($ch); echo curl_getinfo($ch, CURLINFO_HEADER_OUT); //官方文檔描述是「發送請求的字符串」,其實就是請求的header。這個就是直接查看請求header,由於上面容許查看 curl_close($ch); return $result; }
結果以下,很清楚的讓你知道在請求URL的過程當中,發送的header和返回的header信息:dom
GET / HTTP/1.1 Host: www.baidu.com Accept: */* User-Agent: php test HTTP/1.1 200 OK Server: bfe/1.0.8.18 Date: Tue, 04 Jul 2017 01:25:19 GMT Content-Type: text/html Content-Length: 2381 Last-Modified: Mon, 23 Jan 2017 13:27:32 GMT Connection: Keep-Alive ETag: "588604c4-94d" Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform Pragma: no-cache Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/ Accept-Ranges: bytes <!DOCTYPE html> <!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8> ......後面不少,就是百度首頁的全部HTML