[英]PHP - Change file name from url when user downloads file
文件链接都是http://website.com/f/xxx.png/zip/txt等。
我需要对其进行设置,以便如果用户下载该文件,它将以不同的名称下载。
我已经看到如何在普通页面上执行此操作,但是我不知道在完成图像本身链接后如何使其工作。
感谢任何帮助:)
编辑:使用重写史蒂文杰弗里斯发布,
header('Content-Disposition: inline; filename=' . $originalFileName . "'");
header("Content-Type:" . $mimeType);
$im = imagecreatefrompng($filePathOnServer);
imagepng($im);
显示图像和
header('Content-Disposition: attachment; filename=' . $originalFileName . "'");
header("Content-Type:" . $mimeType);
使其他文件下载解决了我遇到的问题。
我认为一个简单的方法是将下载链接重定向到另一个处理下载内容等的脚本。基本上,我会设置一个下载目录,添加一些重写规则,然后创建一个脚本来处理获取的内容输出。
像这样的东西(未经测试):
/path-to-web-root/download/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.* /downloads/handle-downloads.php
/path-to-web-root/download/handle-downloads.php
$url = trim($_SERVER['REQUEST_URI'], '/');
if (preg_match('^#downloads/(?<real_filename>.*?)/(?<options>.*)/(?<fake_filename>.*)$#', $url, $matches)) {
// Double check my regex, but basically pull the real filename from the url here
$actual_file = "/path-to-webroot/f/{$matches['real_filename']}";
$options = explode('/', $matches['options']);
if (in_array('zip', $options)) {
// Handle zip, etc.
}
$fake_filename = $matches['fake_filename'];
if (file_exists($actual_file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($fake_filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($actual_file));
readfile($file);
exit;
}
}
然后,不是将下载链接设为 website.com/f/xxx.png/zip/txt,而是改为 website.com/download/xxx.png/zip/txt/ new-filename.png 。 这将允许您将文件名设置为您想要的任何内容,因为浏览器只会获取 url 末尾的内容。
编辑:我已经包含了readfile 的手册页中的相关代码。
您可以通过设置 header 参数来设置文件响应文件名。
例如:
<?php
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="xyz.png"');
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
...
有关 PHP 标头功能的更多信息,请访问: http : //php.net/manual/en/function.header.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.