English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Basic PHP Tutorial

Advanced PHP Tutorial

PHP & MySQL

PHP Reference Manual

PHP File Download

In this tutorial, you will learn how to force files to download using PHP.

Download files using PHP

通常,您不一定需要使用任何服务器端脚本语言(例如PHP)来下载图像,zip文件,pdf文档,exe文件等。如果此类文件存储在公共可访问的文件夹中,则只需创建一个指向该文件的超链接,每当用户单击链接时,浏览器都会自动下载该文件。

<a href="downloads/test.zip">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download image file</a>
<a href="downloads/<a href="downloads setup.exe">Download EXE file</a>

Clicking on a link pointing to a PDF or image file does not cause it to be directly downloaded to the hard drive. It will only open the file in the browser. In addition, you can save it to the hard drive. However, by default, zip and exe files will be automatically downloaded to the hard drive.

PHP forced download

You can use the PHP readfile() function to force images or other types of files to be directly downloaded to the user's hard drive. Here, we will create a simple image gallery that allows users to click on the mouse to download image files from the browser.

Let's create a name called "image-gallery.php" file, and place the following code inside it.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8>
<title>Simple Image Gallery</title>
<style type="text/css">
    .img-box{
        display: inline-block;
        text-align: center;
        margin: 0 15px;
    }
</style>
</head>
    <?php
    //An array containing example image file names
    $images = array("kites.jpg", "balloons.jpg");
    
    //Traverse the array to create an image gallery
    foreach($images as $image){
        echo '<div class="img-box">;
            echo '<img src="images/' . $image . '" width="200" alt="' . pathinfo($image, PATHINFO_FILENAME) . '">';
            echo '<p><a href="download.html?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
</html>

If you carefully examine the example code above, you will find a download link pointing to the "download.php" file, which URL also contains the image file name as a query string. In addition, we use the PHP urlencode() function to encode the image file name so that it can be safely passed as a URL parameter, as the file name may contain characters that are not safe for URLs.

This is the complete code for the "download.php" file, which can force the download of images.

<?php
if(isset($_REQUEST["file"])){
    //get parameters
    $file = urldecode($_REQUEST["file"]); //decode URL-encoded strings
    /* test whether the file name contains illegal characters
    For example, using the regular expression "..."/” */
    if(preg_match('/^.[^-a-z0-9_]$+[a-z]$/i', $file)){
        $filepath = "images/. $file;
        // 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 the output buffer of the system
            readfile($filepath);
            die();
        } else {
            http_response_code(404);
	        die();
        }
    } else {
        die("Invalid file name!");
    }
}
?>

Similarly, you can force the download of other file formats, such as .doc, pdf files, etc.

example above (the8lineThe regular expressions in the parentheses will completely disallow file names that start or end with a dot character (.), such as, for example, it allows the use of file names like kites.jpg or Kites.jpg, myscript.min.js, etc., but does not allow file names like kites.jpg. or .kites.jpg.

Please see relatedRegular Expressionstutorial to learn regular expressions in detail.