我有一个PHP脚本,可以很好地在我上传的目录中显示所有图像。我想做一个小下载按钮,这样有人可以点击按钮下载图像。我正在为我的公司做这个,这样人们就可以下载我们的标志。
<?php
// Find all files in that folder
$files = glob('grips/*');
// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}
?>
我想我可以做一个按钮,并调用$file
的href,但这只会链接到文件并显示图像。我不确定是否有自动下载。任何帮助都太好了。
只需在download.php
文件中添加一些标题,这样您就可以像这样读取文件:
确保你的数据进入文件,你不希望别人能够下载你的php文件
<?php
// Find all files in that folder
$files = glob('grips/*');
// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" /><br /><a href="/download.php?file='.base64_encode($file).'">Download Image</a>';
}
?>
download.php
$filename = base64_decode($_GET["file"]);
// Data sanitization goes here
if(!getimagesize($filename) || !is_file($filename)){
// Not an image, or file doesn't exist. Redirect user
header("Location: /back_to_images.php");
exit;
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($filename).";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile($filename);