我正在尝试使用PHP& ;;下载一些文件CURL,但我没有看到使用默认建议文件名的简单方法(在HTTP响应头中为
内容 – 处理:附件;文件名= foo.png
).是否有更简单的方法来获取完整的标题,解析文件名并重命名?
解决方法:
$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,因为使用临时文件这类事情很草率,但由于某些原因我无法正常工作.但至少你明白了……
标签:php,curl
来源: https://codeday.me/bug/20190713/1452356.html