1

我有一个 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 . '" />';
        }

    ?>

我想我可以只制作一个按钮并调用 href ,$file但这只会链接到文件并显示图像。我不确定它是否会自动下载。任何帮助都会很棒。

4

1 回答 1

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>';
    }

?>

下载.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); 
于 2013-05-29T18:18:32.853 回答