PHP的curl獲取header信息


PHP的curl功能十分強大,簡單點說,就是一個PHP實現瀏覽器的基礎。

最常用的可能就是抓取遠程數據或者向遠程POST數據。但是在這個過程中,調試時,可能會有查看header的必要。

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信息:

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM