我有一个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,但这只会链接到文件并显示图像。我不确定是否自动下载。任何帮助都会很棒。
答案 0 :(得分:0)
只需在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);