Php download file from directory

This short tutorial will help you to learn how to download a file with PHP.

Just follow the examples below to easily meet that goal.

If you want to make different types of files or images load the files directly into the drive of the user with PHP, you can run the readfile() function.

Let’s see how to do it on the example of creating an image gallery, which will help the users to download image files using just one click.

In the example below, an image-gallery.php is generated and a code is placed inside it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Simple Image Gallery</title>
    <style>
      .img-box {
        display: inline-block;
        text-align: center;
        margin: 0 15px;
      }
    </style>
  </head>
  <body>
    <?php
    // Array encompassing sample image file names
    $images = array("kites.jpg", "balloons.jpg");
    
    // Looping through the array to generate 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.php?file=' . urlencode($image) . '">Download</a></p>';
        echo '</div>';
    }
    ?>
  </body>
</html>

So, in the example above, the download link points to the download.php file. The URL, on its turn, encompasses an image file name, just as a query string. Also, you can notice, that the urlencode() function is applied for encoding the image file names in a way that they may be safely passed like a URL parameter. The reason is that file names may include unsafe URL characters. The entire code of the download.php, forcing image download looks as follows:

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

    /* Check if the file name includes illegal characters
    like "../" 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 system output buffer
            readfile($filepath);
            die();
        } else {
            http_response_code(404);
	        die();
        }
    } else {
        die("Invalid file name!");
    }
}
?>

Other file formats such as pdf, doc, and so on, can also be downloaded in the way, demonstrated above.

It is crucial to consider that in the example above, the regular expression (line 8) doesn’t allow files with the names that start or end with a dot (.). For example, you can use filenames such as books.jpg or Books.jpg but can’t use books.jpg., .kites.jpg, and so on.

Normally, a hyperlink can be used to open a file on the browser. In such a case, the file can download from the browser manually. If you want to download the file dynamically and save it on the local drive automatically, force the browser to download the file instead of displaying it. Force file download functionality allows the user to download files in PHP where the requested files are downloaded forcefully without rendering on the browser. In this tutorial, we are going to show how to download a file from a directory or server in PHP.

Using the header() and readfile() function, you can easily download a file in PHP. Here we’ll provide the example PHP code to force download file in PHP. Also, this simple PHP script helps to implement a download link that downloads a file from the directory. The following example script can be used to download any type of file like text, image, document, pdf, zip, etc.

Download File in PHP

<?php 
// Define file name and path
$fileName 'Brochure.pdf';
$filePath 'files/'.$fileName;

if(!empty(

$fileName) && file_exists($filePath)){
    
// Define headers
    
header("Cache-Control: public");
    
header("Content-Description: File Transfer");
    
header("Content-Disposition: attachment; filename=$fileName");
    
header("Content-Type: application/zip");
    
header("Content-Transfer-Encoding: binary"); // Read the file
    
readfile($filePath);
    exit;
}else{
    echo 
'The file does not exist.';
}

In the web application, you need to provide a hyperlink to allow the user to download files from the server dynamically. Use the below sample code to display an HTML link to download a file from the directory using PHP.
HTML Code:

<a href="download.php?file=Brochure.pdf">Download File</a>

PHP Code (download.php):

<?php if(!empty($_GET['file'])){ 
    
// Define file name and path
    
$fileName basename($_GET['file']);
    
$filePath 'files/'.$fileName;

    if(!empty(

$fileName) && file_exists($filePath)){
        
// Define headers
        
header("Cache-Control: public");
        
header("Content-Description: File Transfer");
        
header("Content-Disposition: attachment; filename=$fileName");
        
header("Content-Type: application/zip");
        
header("Content-Transfer-Encoding: binary"); // Read the file
        
readfile($filePath);
        exit;
    }else{
        echo 
'The file does not exist.';
    }
}
?>

Force Download File from Remote Server in PHP

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

How can I download file from PHP code?

PHP enables you to download file easily using built-in readfile() function. The readfile() function reads a file and writes it to the output buffer..
<? ... .
header('Content-Type: application/octet-stream');.
header("Content-Transfer-Encoding: utf-8");.

How do I set PHP to download to a specific directory?

Steps to download the file:.
Initialize a file URL to the variable..
Create cURL session..
Declare a variable and store the directory name where the downloaded file will save..
Use the basename() function to return the file basename if the file path is provided as a parameter..
Save the file to the given location..

How do I download a PHP file from browser?

Check Download Links.
Download.html..
Output. The following dialog box will appear to download the file after clicking the zip file link. ... .
Syntax. int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] ).
download2.html..
download.php..
Output. ... .
download3.html..
download2.php..

How can download file from server to local machine in PHP?

2 Answers.
Create a file from it and redirect the user to the file by using header('Location: /path/to/file.txt');.
Insert the following header: header('Content-disposition: attachment; filename=path/to/file.txt');.