php根據Http請求頭部資訊下載檔案
阿新 • • 發佈:2019-01-25
朋友遇到一個問題,php訪問一個下載地址,獲得的只有地址的請求值,而沒有問題,經過大神的指導發現,原來下載地址有經過校驗,要在瀏覽器環境下才能下載,用php的header模擬瀏覽器環境,就能下載了。大神的解決方法:先用瀏覽器訪問這個地址,獲得這個地址的頭部資訊
在程式碼裡模擬瀏覽器訪問。大神的程式碼如下:
function getpdf($url){
$header=['Host:xxxx',
'User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0',
'Accept:text/html,/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language:en-US,applicationzh-CN;q=0.8,zh;q=0.5,en;q=0.3',
'Accept-Encoding:gzip, deflate',
'Connection:keep-alive',
'Upgrade-Insecure-Requests:1'
];
$ch = curl_init();
$fp=fopen('girl.pdf', 'w');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
$output = curl_exec($ch);
curl_close($ch);
file_put_contents('dowm.pdf', $output);
echo $output;
}