使用PHP下载重命名的文件 [英] Download a renamed file with PHP

查看:105
本文介绍了使用PHP下载重命名的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个PHP脚本,下载一个名称和一个版本的文件。文件将存储在服务器上,如下所示:

  /dl/Project1/1.0.txt 
/ dl / Project1 / 1.1.txt
/dl/Project2/2.3.jar
/dl/Project2/2.3.1.jar

检索这些文件的路径如下所示:

  download.php? name = Project1& type = txt& version = 1.0 
download.php?name = Project1& type = txt& version = 1.1
download.php?name = Project2& type = jar& version = 2.3
download.php?name = Project2& type = jar& version = 2.3.1

实际下载文件时出现问题。在这个例子中,我希望前两个文件都可以作为Project1.txt下载,而我想要最后两个文件作为Project2.jar下载。如何临时重命名这些工作?

解决方案

发送一个定义文件名的头文件。

  $ filename = $ name。  。 $类型; 
header('Content-Description:File Transfer');
header('Content-Type:application / octet-stream');
header('Content-Disposition:attachment; filename ='。$ filename);
header('Content-Transfer-Encoding:binary');
header('Expires:0');
header('Cache-Control:must-revalidate');
header('Pragma:public');
header('Content-Length:'。filesize($ file));

我附加了标题,因为你也应该发送这些。这只是一个修改示例,您可以参阅 readfile


I am making a PHP script that will download a file given a name and a version. The files will be stored on the server like this:

/dl/Project1/1.0.txt
/dl/Project1/1.1.txt
/dl/Project2/2.3.jar
/dl/Project2/2.3.1.jar

And the paths to retrieve such files would look like this:

download.php?name=Project1&type=txt&version=1.0
download.php?name=Project1&type=txt&version=1.1
download.php?name=Project2&type=jar&version=2.3
download.php?name=Project2&type=jar&version=2.3.1

The issue arises when actually downloading the files. In this example, I want the first two files to both download as Project1.txt, and I want the last two to download as Project2.jar. How can I rename these temporarily to allow this to work?

解决方案

Send out a header defining the file's name.

$filename = $name . "." . $type;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $filename);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));

I've included additional headers, since you should send out these as well. This is just a modified example of what you can see in the PHP documentation on readfile.

这篇关于使用PHP下载重命名的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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