我正在尝试使用 PHP 和 CURL 下载一些文件,但我没有看到使用默认建议文件名(在 HTTP 响应 header 中为
Content-Disposition:附件;文件名=foo.png
)。有没有更简单的方法然后获取完整的 header 、解析文件名并重命名?
最佳答案
<?php
$targetPath = '/tmp/';
$filename = $targetPath . 'tmpfile';
$headerBuff = fopen('/tmp/headers', 'w+');
$fileTarget = fopen($filename, 'w');
$ch = curl_init('http://www.example.com/');
curl_setopt($ch, CURLOPT_WRITEHEADER, $headerBuff);
curl_setopt($ch, CURLOPT_FILE, $fileTarget);
curl_exec($ch);
if(!curl_errno($ch)) {
rewind($headerBuff);
$headers = stream_get_contents($headerBuff);
if(preg_match('/Content-Disposition: .*filename=([^ ]+)/', $headers, $matches)) {
rename($filename, $targetPath . $matches[1]);
}
}
curl_close($ch);
我最初尝试使用 php://memory而不是 /tmp/headers
,因为对这种事情使用临时文件是草率的,但出于某种原因我无法让它工作。但至少你明白了......
或者,您可以使用 CURLOPT_HEADERFUNCTION
关于php - 使用 CURL 下载时使用默认文件名 (content_disposition),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2072643/