導讀:
curl請求時添加請求頭信息可以模擬真人操作,不容易被當成是爬蟲機器人(采集),從而可以繞過Incapsula等安全驗證機制。
1、首先使用瀏覽器(示例使用的是火狐瀏覽器)訪問接口網址,使用F12調試,查看請求頭信息,如下:
2、實現代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
<?php /** * 開始訪問請求 * @param $url * @return bool|string */ function fetch_url( $url ) { $header = FormatHeader( $url ); $useragent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0' ; $timeout = 120; $ch = curl_init( $url ); curl_setopt( $ch , CURLOPT_FAILONERROR, true); //設置請求頭信息 curl_setopt( $ch , CURLOPT_HTTPHEADER, $header ); //不取得返回頭信息 curl_setopt( $ch , CURLOPT_HEADER, 0); // 關閉https驗證 curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER, false); curl_setopt( $ch , CURLOPT_SSL_VERIFYHOST, false); curl_setopt( $ch , CURLOPT_FOLLOWLOCATION, true ); curl_setopt( $ch , CURLOPT_ENCODING, "" ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch , CURLOPT_AUTOREFERER, true ); curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch , CURLOPT_TIMEOUT, $timeout ); curl_setopt( $ch , CURLOPT_MAXREDIRS, 10 ); curl_setopt( $ch , CURLOPT_USERAGENT, $useragent ); $content = curl_exec( $ch ); if (curl_errno( $ch )) { echo 'Error:' . curl_error( $ch ); } else { return $content ; } curl_close( $ch ); } //添加請求頭 function FormatHeader( $url ) { // 解析url $temp = parse_url ( $url ); $query = isset( $temp [ 'query' ]) ? $temp [ 'query' ] : '' ; $path = isset( $temp [ 'path' ]) ? $temp [ 'path' ] : '/' ; $header = array ( "POST {$path}?{$query} HTTP/1.1" , "Host: {$temp['host']}" , "Referer: http://{$temp['host']}/" , "Content-Type: text/xml; charset=utf-8" , 'Accept: application/json, text/javascript, */*; q=0.01' , 'Accept-Encoding:gzip, deflate, br' , 'Accept-Language:zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2' , 'Connection:keep-alive' , 'User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0' , 'X-Requested-With: XMLHttpRequest' , ); return $header ; } ?> |
3、調用示例:
1
2
3
4
5
|
<?php //lcg_value() 返回范圍為 (0, 1) 的一個偽隨機數 $url = "http://www.xxx.com/getdata.php?v=" .lcg_value(); //訪問網址 $html = fetch_url( $url ); |
到此這篇關于php的curl攜帶header請求頭信息實現http訪問的方法的文章就介紹到這了,更多相關php的curl請求頭信息實現http訪問內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq15577969/article/details/110913311