how to force file download in php

How to Force Download File in PHP

Sometimes you may need to make users to download files when they click links on your website, without opening or streaming that file in their browser. In this article, we will look at how to force download file in PHP. This is useful in case your file has many audio/video files that users typically stream on their browser without downloading, in which case, your server load increases due to too many open connections.

Actually, you don’t need to use any PHP code to force download a file. You can simply set the URL’s content-disposition header and content-type header in .htaccess file of your Apache server. This will force Apache to send file downloads. Here is how to force download in Apache.


How to Force Download File in PHP

Here are the steps to force download file in PHP.


1. Create php file

Open terminal and create download.php file. This will have the main function for serving file downloads. We have created the file in our website root folder /var/www/html. If your website root folder is different, please update the following path as per your requirement.

$ sudo vi /var/www/html/download.php

We will use readfile() function to serve the file download. Add the following lines to the above file. Our files are located at /var/www/html/downloads/ folder. If your files are located in a different location, please update the path below in bold as per your requirement.

<?php
if(isset($_REQUEST["file"])){
    // get filename from request URL-encoded string
    $file = urldecode($_REQUEST["file"]); 
   
    // check for illegal characters in filename
        
    if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
        $filepath = "/var/www/html/downloads/" . $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 system output buffer
            flush(); 
            readfile($filepath);
            die();
        } else {
            http_response_code(404);
            die();
        }
    } else {
        die("Download cannot be processed");
    }
}
?>


2. Create index.html

Next, we will create an index.html file with links to file downloads. Open terminal and run the following command to create index.html.

$ sudo vi index.html

Add the following lines to index.html file.

<?php
  
// Array containing sample pdf file names
$files = array(
    "test1.pdf",
    "test2.pdf"
);
$names = array(
    "Test 1",
    "Test 2"
);
  
// Loop through array to create library
for ($i = 0;$i <= 1;$i++)
{
    echo $names[$i];
    echo '<p>
    <a href="downloader.php?file=' . urlencode($files[$i]) . '">Download</a></p>';
  
}
?>

The above file will simply create two anchor links for file downloads.

When you click on either of the links in your index.html page, it will automatically send requests to download.php which will start the file download.

Forcing file download is very useful in case your website contains many audio/video files that are typically streamed over the net. When you force download your server will send the file and close connection. But when a user streams the file it keeps the connection open and increases server load unnecessarily.

The above method is useful if you want to force users to download but do not want the downloads to publicly accessible.

However, as mentioned earlier, you may also force download in Apache without any PHP coding. You may also place these files in a publicly accessible URL so that clicking them automatically starts downloads in browser.

Also read:

How to Force File Download in NGINX
How to List All Users in Ubuntu
Apache Configure Multiple Virtual Hosts
How to Clean up disk space in Linux
How to Add Response Header in NGINX

Leave a Reply

Your email address will not be published.