Php 从URL保存图像

Php 从URL保存图像,php,curl,file-get-contents,Php,Curl,File Get Contents,我想用PHP中的URL获取一组图像。我试过使用file\u get\u contents和curl。下面是我尝试使用的代码 $image = file_get_contents('http://user:pwd@server/directory/images/image1.jpg'); file_put_contents('D:/images/image1.jpg', $image); 及 在这两种情况下,我都会遇到以下错误: 401 - Unauthorized : Access is de

我想用PHP中的URL获取一组图像。我试过使用
file\u get\u contents
curl
。下面是我尝试使用的代码

$image = file_get_contents('http://user:pwd@server/directory/images/image1.jpg');
file_put_contents('D:/images/image1.jpg', $image);

在这两种情况下,我都会遇到以下错误:

401 - Unauthorized : Access is denied due to invalid credentials.

密码有一个特殊字符。我无法将其更改为普通密码,因为密码策略不允许它。

我看不到您告诉CURL使用身份验证的地方:

curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
我认为这也可能是因为您没有使用cookies,请启用它们:

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

这条线的等价物是

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的实现。例如:。不同的库或不同的语言为base64编码/解码实现了不同的RFC。例如,在某些实现中,它使用
+
/
字符,而一些实现中使用
\
-
字符


假设您的curl正在发送base64字符串,因为授权为
xyz+12=
,但您的服务器希望该字符串为
xyz\u 12=
。因此,它显然无法解码。

当使用
file\u get\u contents()
时,您需要创建一个包含身份验证头的特殊流上下文。curl代码应该很好。什么是特殊字符?特殊字符是否转义?特殊字符是下划线。不确定,如何逃逸。@hek2mgl我试着使用上下文,如下所示$context=stream\u context\u create(数组('http'=>array('header'=>“Authorization:Basic”).base64\u encode(“user:Pwd\u 123”));还是一样的错误。我试过使用CURLOPT_USERPWD。但这没有帮助。在代码中添加了以下内容:curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);curl_setopt($ch,CURLOPT_USERPWD,'user:Pwd_123');仍然得到相同的错误。
curl_setopt($ch, CURLOPT_HTTPHEADER, 
      array("Authorization: Basic ".base64_encode("user:pwd")));

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