php - 如何使用 cURL 下载在 PHP 中使用 HTTP 摘要身份验证保护的文件?

标签 php linux http authentication curl

我在下载使用 HTTP 摘要身份验证保护的文件时遇到问题。我已经设法让命令行版本的 curl 工作:

curl --location -u Myusername:mypassword -C - --digest -k https://www.thefile.com/file.xml.gz > /location/to/download/file.xml.gz

但是,当我尝试使用 PHP cURL 进行连接时,我什么也没得到,也没有想出如何指定下载文件的位置(如果连接成功的话):

$username = "Myusername";
$password = "mypassword";
$url = "https://www.thefile.com/file.xml.gz";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_r($output);
print_r($info);

谁能阐明如何将上述 cURL 命令行版本转换为 PHP 版本?我坚持我做错/遗漏的事情。

谢谢!

最佳答案

要指定您需要的输出文件位置,可以创建一个本地文件句柄来写出实际的文件数据,并将其存储在本地。

将以下内容添加到上面的示例中...

$filename = "file.xml.gz";
$filehandle = fopen($filename, "w+");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FILE, $filehandle);

curl_close 之后

fclose($filehandle);

要调试您的摘要身份验证,请启用写入 header 。这会为您提供另一个包含返回 header 的文件。通常是 401 unauthorized,带有新的 nonce 值,然后在发送新摘要时返回 200 ok。

$headerfilename = "file.xml.gz.header";
$headerfilehandle = fopen($headerfilename, "w+");
curl_setopt($ch, CURLOPT_WRITEHEADER, $headerfilehandle);

curl_close 之后

fclose($headerfilehandle);

关于php - 如何使用 cURL 下载在 PHP 中使用 HTTP 摘要身份验证保护的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37283612/

相关文章:

java - 无法通过 WiFi 连接,但可以通过移动数据连接

Linux:如何将目录中的所有文件重命名为大写?

用于 Linux 的 RegEx 和 grep

linux - for循环内的iconv找不到输出目录

Java HttpURLConnection InputStream.close() 挂起(或工作时间过长?)

java - Android,通过 HTTP 将 XML 字符串发送到服务器

php - MS SQL 2005 自动递增错误

PHP 购物车产品编号

php - 为什么 html 文本输入名称会导致提交输入无法设置?

http - 所有 GWT 浏览器都有 2 个连接限制吗?