用php curl模塊來測試網頁有沒有重定向

 

  1. //下面是測試用的URL列表 
  2. $urls = array
  3.     "http://www.baidu.com"
  4.     "http://www.google.com" 
  5. ); 
  6. /* 
  7.  * 測試用的瀏覽器信息 
  8.  *   
  9.  
  10.  
  11. */ 
  12. $browsers = array
  13.     "standard" => array ( 
  14.         "user_agent" => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)"
  15.         "language" => "en-us,en;q=0.5" 
  16.         ), 
  17.     "iphone" => array ( 
  18.         "user_agent" => "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3"
  19.         "language" => "en" 
  20.         ), 
  21.     "french" => array ( 
  22.         "user_agent" => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; .NET CLR 2.0.50727)"
  23.         "language" => "fr,fr-FR;q=0.5" 
  24.         ) 
  25. ); 
  26.  
  27. foreach ($urls as $url) { 
  28.     echo "[URL]: $url<br>"
  29.     foreach ($browsers as $test_name => $browser) { 
  30.         //初始化curl 
  31.         $ch = curl_init(); 
  32.         // 設置 url 
  33.         curl_setopt($ch, CURLOPT_URL, $url); 
  34.         // 設置瀏覽器的特定header 
  35.         //CURLOPT_HTTPHEADER: An array of HTTP header fields to set.   
  36.         curl_setopt($ch, CURLOPT_HTTPHEADER, array
  37.                 "User-Agent: {$browser['user_agent']}"
  38.                 "Accept-Language: {$browser['language']}" 
  39.             )); 
  40.         // 頁面內容我們並不需要 
  41.         curl_setopt($ch, CURLOPT_NOBODY, 1); 
  42.         // 只需返回HTTP header 
  43.         curl_setopt($ch, CURLOPT_HEADER, 1); 
  44.         // 返回結果,而不是輸出它 
  45.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  46.         //執行curl操作 
  47.         $output = curl_exec($ch); 
  48.         curl_close($ch); 
  49.         // 有重定向的HTTP頭信息嗎? 
  50.         //preg_match() 返回 pattern 所匹配的次數。 
  51.         //要麼是 0 次(沒有匹配)或 1 次,因爲 preg_match() 
  52.         // 在第一次匹配之後將停止搜索。preg_match_all() 則相反,會一直搜索到 subject 的結尾處。如果出錯 preg_match() 返回 FALSE。  
  53.  
  54.          
  55.         if (preg_match("!Location: (.*)!"$output$matches)) { 
  56.             echo "$test_name: redirects to $matches[1]\n"
  57.         } else { 
  58.             echo "$test_name: no redirection\n"
  59.         } 
  60.     } 
  61.     echo "<br><br>"

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章