我想用PHP中的URL抓取一組圖像。我試過使用file_get_contents
和curl
。以下是我嘗試使用的代碼。從URL保存圖像
$image = file_get_contents('http://user:[email protected]/directory/images/image1.jpg');
file_put_contents('D:/images/image1.jpg', $image);
和
$url = 'http://server/directory/images/image1.jpg';
$localFilePath = 'D:/images/image1.jpg';
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
curl_setopt($ch, CURLOPT_USERPWD, "user:pwd");
$raw = curl_exec($ch);
curl_close ($ch);
if(file_exists($localFilePath)){
unlink($localFilePath);
}
$fp = fopen($localFilePath,'wb');
fwrite($fp, $raw);
fclose($fp);
在這兩種情況下,我收到以下錯誤:
401 - Unauthorized : Access is denied due to invalid credentials.
密碼具有特殊字符。我無法將其更改爲普通密碼,因爲密碼策略不允許。
使用'file_get_contents()'時,您需要創建一個包含Authentication標頭的特殊流上下文。捲曲代碼應該沒問題。什麼是特殊字符? – hek2mgl
特殊字符是否被轉義? – DanFromGermany
特殊字符是下劃線。不知道,如何逃避它。 –