在使用CURL下载时使用默认文件名(content_disposition) [英] Using the default filename (content_disposition) when downloading with CURL

查看:296
本文介绍了在使用CURL下载时使用默认文件名(content_disposition)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图下载一些文件与PHP& CURL,但我没有看到一个简单的方法使用默认的建议文件名(这是在HTTP响应头中

I'm trying to download some files with PHP & CURL, but I don't see an easy way to use the default suggested filename (which is in the HTTP response header as

Content-Disposition:attachment; filename = foo .png

Content-Disposition: attachment; filename=foo.png

)。是否有更简单的方法,然后获取完整的标题,解析文件名并重命名?

). Is there an easier way then get the full header, parse the file name and rename?

推荐答案

<?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 ,因为使用临时文件的东西是马虎,但由于某种原因,我不能得到那个工作。但至少你得到的想法...

I initially tried to use php://memory instead of /tmp/headers, 'cause using temp files for this sort of thing is sloppy, but for some reason I couldn't get that working. But at least you get the idea...

或者,你可以使用 CURLOPT_HEADERFUNCTION

这篇关于在使用CURL下载时使用默认文件名(content_disposition)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆