我怎样才能使用php下载图像文件

时间:2017-11-10 09:24:13

标签: php

我尝试使用php下载图像文件,我在谷歌上搜索并找到了一些代码,但是当我试用它时,它不能正常工作,有些人应该帮助我。

的index.php

<?php
    // Array containing sample image file names
    $images = array("img5.jpg", "img2.jpg");

    // Loop through array to create image gallery
    foreach($images as $image){
        echo '<div class="d_c">';
            echo '<img src="' . $image . '" width="200" alt="' .  pathinfo($image, PATHINFO_FILENAME) .'">';
            echo '<p><a href="download.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>

的download.php

<?php
if(isset($_REQUEST["file"])){
    // Get parameters
    $file = urldecode($_REQUEST["file"]); // Decode URL-encoded string
    $filepath = "forum";

    // Process download
    if(file_exists($filepath)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filepath));
        flush(); // Flush system output buffer
        readfile($filepath);
        exit;
    }
}
?>

0 个答案:

没有答案