php 下载时重命名文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1801076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:53:29  来源:igfitidea点击:

Renaming files when downloading it

php

提问by Boffin

I want to rename file when user downloads it.

我想在用户下载文件时重命名文件。

Right now, I'm sending content-disposition and content-length headers and then send file to user with fpassthru PHP function.

现在,我正在发送 content-disposition 和 content-length 标头,然后使用 fpassthru PHP 函数将文件发送给用户。

But there is 3 problems with this method:

但是这种方法有 3 个问题:

  1. If I'm sending big (above 3-4Gb) files this way, then my PHP script runs too much time and may be killed by timeout.
  2. If user cancels the download, PHP script continue to read and send the file
  3. If user pauses the download, he cannot resume it later.
  1. 如果我以这种方式发送大(3-4Gb 以上)文件,那么我的 PHP 脚本运行时间过长,可能会因超时而终止。
  2. 如果用户取消下载,PHP 脚本会继续读取并发送文件
  3. 如果用户暂停下载,他将无法在以后继续下载。

Is there any nicer way to rename files on download?

有没有更好的方法来重命名下载的文件?

回答by RienNeVaPlu?s

Since the question was asked, some time has gone by and html5gave us a different approach to this:

自从提出这个问题以来,一段时间过去了,html5给了我们一种不同的方法来解决这个问题:

<a href="someWeiredFileName.rar" download="coolFilename.rar">Download</a>

The attributedownload(learn more) defines the default filenamefor storing the file on the clients computer (he'll still be able to change it!).

attribute下载了解更多)定义了默认filename存储在客户计算机上的文件(他仍然能够去改变它!)。

Note: this won't affect anything on your server.

注意:这不会影响您服务器上的任何内容。

回答by powtac

<?php
header('Content-type: application/pdf');

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

// The PDF source is in original.pdf
readfile('original.pdf');
?> 
  1. The file will be offered for download as "downloaded.pdf" while its original name was "original.pdf".
  1. 该文件将作为“downloaded.pdf”提供下载,而其原始名称为“original.pdf”。

Pseudo code

伪代码

while(1) {
    Echo "..."; //<-- send this to the client
    if (connection_status()!=0){
    die;
    }
}
  1. You can stop the PHP script if a user cancels the browser by using connection_status()

  2. HTTP can not reconnect a closed connection. FTP can!

  1. 如果用户使用以下命令取消浏览器,您可以停止 PHP 脚本 connection_status()

  2. HTTP 无法重新连接已关闭的连接。FTP可以!

回答by Atli

For the third point, you could try using the HTTP Rangeheaders.
If the user has a resume-capable download client, it should send those headers to your script, which you could use to pinpoint exactly which parts of the file to send.

对于第三点,您可以尝试使用HTTP 范围标头。
如果用户有一个支持恢复的下载客户端,它应该将这些标头发送到您的脚本,您可以使用它来精确确定要发送的文件部分。