如何强制文件在PHP中下载 [英] How to force a file to download in PHP
问题描述
我有图像列表,我想要一个下载链接与每个图像,以便用户可以下载图像。
I have list of images and I want a "Download" link along with every image so that user can download the image.
所以有人可以指导我如何为php中的任何文件提供下载链接?
so can someone guide me How to Provide Download link for any file in php?
编辑
我希望在点击下载链接时显示一个下载面板,我不想导航到浏览器中显示的图像
I want a download panel to be displayed on clicking the download link I dont want to navigate to image to be displayed on the browser
推荐答案
如果您想强制下载,可以使用以下内容:
If you want to force a download, you can use something like the following:
<?php
// Fetch the file info.
$filePath = '/path/to/file/on/disk.jpg';
if(file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);
// Output headers.
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
// Output file.
readfile ($filePath);
exit();
}
else {
die('The provided file path is not valid.');
}
?>
如果您只需使用正常链接链接到此脚本,该文件将被下载。
If you simply link to this script using a normal link the file will be downloaded.
顺便提一句,上面的代码片段需要在页面开始执行(在任何标题或HTML输出发生之前)。还要注意,如果你决定创建一个基于这个功能来下载任意文件 - 你需要确保你阻止目录遍历( realpath 是方便的),只允许从定义的区域下载等,如果您接受$ _GET或$ _POST的输入。
Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files - you'll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you're accepting input from a $_GET or $_POST.
这篇关于如何强制文件在PHP中下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!