最近把一個抓檔案的程式由 wget 換成 php 的 http_get 卻發現有部分情況檔案無法正常抓下來 仔細 trace 一個個步驟,發現是網址 301 or 302 惹的禍 換句話說也就是被 wget 養壞習慣 因為當 wget 遇到 301,302時, 他會自動繼續幫你爬下去抓到目的地的檔案為止 可是換成 http_get 後,他就真的很單純的做好這個 url 的處理 把結果放到回傳的參數中, 自己必須處理接下來遇到的情況 譬如說 301,302,在 response 的 header中 就把接下來要導過去的網址放在 Location 這個參數中 要抓檔案,就要再 http_get 一次 Location url 要注意的是,一定要處理防止 loop 情況的產生 不然你的程式就一直無限的在 http_get 了 sample code: $data = @http_get($url, $option, $ret); $message = @http_parse_message($data); if (301 == $message->responseCode or 302 == $message->responseCode) {   $data2 = @http_get($message->headers['Location'], $option, $ret);   // TODO 如果又遇到 301 or 302 就要在導下去, 不過要確保不要 loop } PS: 這篇是用行動管家 po 出來的 XD
文章標籤
全站熱搜
創作者介紹
創作者 ieon 的頭像
ieon

I'm ieon

ieon 發表在 痞客邦 留言(2) 人氣(380)