我想一个简单的方法来做到这一点。将下载链接重定向到另一个脚本处理下载什么,等基本上,我会设置一个下载目录,添加一些重写规则,然后创建一个脚本来处理输出。
像这样(未经):
/path-to-web-root/download/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.* /downloads/handle-downloads.php
/路径到Web根/下载/处理的下载。 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。这将允许您将文件名设置为任何您想要的文件名,因为浏览器只会采用网址末尾的内容。
编辑:我已经包含从readfile's manual page相关的代码。
这似乎是我可以适应我的情况,非常感谢。 我会尝试它,如果它在早上第一件事情起作用,则标记为已解决。 –
我遇到了使用readfile显示图像的问题,但您的答案帮助我回答了实际问题,所以谢谢!我正确设置了MIME的东西,但页面仍以文本形式读取图像数据,这里有帮助的线索吗? :b –
是的,对不起,我的例子非常普遍且很少。您仍然必须根据文件等设置正确的标题。您可能想使用函数'imagepng'而不是'readfile':http://php.net/manual/en/function.imagepng.php –