下载远程文件并重命名文件 - &客户端的文件类型

时间:2014-04-10 08:24:10

标签: php file download rename

我正在开发一个项目,在客户端,它应该从远程URL开始下载。

我目前使用cURL,但问题是它下载到服务器,而不是客户端的浏览器(询问保存位置)。

网址如下所示:

http://r13---sn-5hn7snee.googlevideo.com/videoplayback?expire=138181&mv=u&ipbits=0&clen=7511717&fexp=929447,913430,930802,916612,902546,937417,913434,936916,934022,936921,936923&ms=au&mt=1396164&itag=247&key=yt5&source=youtube&ip=2a00:7143:100:1:225:90ff:fe52:b3ad&sparams=clen,dur,gir,id,ip,ipbits,itag,lmt,source,upn,expire&signature=DBDCE9EFFC094C0FC653610C8FAAF367EA942CC4C6EF3971A186C&upn=0JQJ6yqyYPo&sver=3&gir=yes&lmt=13960601932&dur=130.133&id=17f0fd8b&size=1280x720,type=video/mp4

当从URL下载时,文件名将是'videoplayback'而没有任何文件扩展名。所以我需要一个自定义文件名和.mp4作为文件类型。 (适用于下面的cURL代码),但它写入服务器而不是客户端下载。

function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
    return false;
}

while (!feof($rh)) {
    if (fwrite($wh, fread($rh, 4096)) === FALSE) {
        return false;
    }
    echo ' ';
    flush();
}

fclose($rh);
fclose($wh);

return true;
}

$result = download('http://r13---sn-5hn7snee.googlevideo.com/videoplayback?expire=138181&mv=u&ipbits=0&clen=7511717&fexp=929447,913430,930802,916612,902546,937417,913434,936916,934022,936921,936923&ms=au&mt=1396164&itag=247&key=yt5&source=youtube&ip=2a00:7143:100:1:225:90ff:fe52:b3ad&sparams=clen,dur,gir,id,ip,ipbits,itag,lmt,source,upn,expire&signature=DBDCE9EFFC094C0FC653610C8FAAF367EA942CC4C6EF3971A186C&upn=0JQJ6yqyYPo&sver=3&gir=yes&lmt=13960601932&dur=130.133&id=17f0fd8b&size=1280x720,type=video/mp4');

if (!$result)
     throw new Exception('Download error...');

所以我的问题是如何将其转换为如此重命名文件并将扩展名更改为mp4,然后在客户端下载文件。

由于

1 个答案:

答案 0 :(得分:0)

首先将正确的标题输出到客户端,以便它知道如何处理文件然后回显文件内容。所以试试这个:

<?php
// ... fetch the file using CURL and store it (in memory or on file system) ...

// Set the content type
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// ... echo/output the file contents to the browser...
?>

在PHP文档中查看“Example #1 Download dialog”。

另外,你提到你使用的是CURL,我在你的代码中没有看到它。

相关问题