2014-02-12 170 views
0

我想用PHP中的URL抓取一組圖像。我試過使用file_get_contentscurl。以下是我嘗試使用的代碼。從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. 

密碼具有特殊字符。我無法將其更改爲普通密碼,因爲密碼策略不允許。

+0

使用'file_get_contents()'時,您需要創建一個包含Authentication標頭的特殊流上下文。捲曲代碼應該沒問題。什麼是特殊字符? – hek2mgl

+0

特殊字符是否被轉義? – DanFromGermany

+0

特殊字符是下劃線。不知道,如何逃避它。 –

回答

0

我不要看到你告訴捲曲使用驗證的地方:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY); 

我想這也可能是因爲你不使用的cookies是,使他們:

curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); 
+0

嗯,我試過使用CURLOPT_USERPWD。但是這並沒有幫助。 –

+0

將此添加到代碼中:curl_setopt($ ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY); curl_setopt($ ch,CURLOPT_USERPWD,'user:Pwd_123'); 仍然收到相同的錯誤。 –

0

這條線的等值是

curl_setopt($ch, CURLOPT_USERPWD, "user:pwd"); 

這一個,你可以試試這個通過替換你的一個

curl_setopt($ch, CURLOPT_HTTPHEADER, 
     array("Authorization: Basic ".base64_encode("user:pwd"))); 

// also you can try by changing +/characters into _- 

現在來談談。 Base64有幾種基於RFC的實現。例如:RFC3538。不同的庫或不同的語言爲base64編碼/解碼實現不同的RFC。例如,在某些實施中,它使用+/字符,有些使用_-字符。

因此可以說你的curl發送授權的base64字符串是xyz+12=,但你的服務器期望字符串爲xyz_12=。所以它顯然無法解碼。