【发布时间】:2014-02-12 15:47:24
【问题描述】:
我想使用 PHP 中的 URL 获取一组图像。我试过使用file_get_contents 和curl。以下是我尝试使用的代码。
$image = file_get_contents('http://user:pwd@server/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()时,您需要创建一个包含身份验证标头的特殊流上下文。卷曲代码应该没问题。什么是特殊字符? -
特殊字符是否转义?
-
特殊字符是下划线。不确定,如何逃脱它。
-
@hek2mgl 我尝试使用如下上下文。 $context = stream_context_create(array('http' => array('header' => "授权:基本".base64_encode("user:Pwd_123"))));还是一样的错误。
标签: php curl file-get-contents