Open In App

How to force a file to get downloaded in PHP?

Last Updated : 07 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

To force a file to get downloaded, there is no need to use the PHP script if you want to keep it simple. If such kind of file is stored in a publicly accessible folder, just create a hyperlink pointing to that file. When the user clicks the file link then the file will be downloaded. You can check the first example of how to trigger a file download when clicking an HTML button article.

Forcing a file to download using PHP: We will be using PHP here as the server-side scripting language. In PHP, this can be done by using readfile() function. The main function of readfile() is to output a file. On clicking any of the hyperlinks the respective file will be downloaded by the browser as shown. The regular expression(regex) validation in the above example using preg_match() function will simply not allow insertion of any illegal character.

  • Script: This script is downloader.php which will be responsible for downloading the files.




    <?php
    if(isset($_REQUEST["file"])){
        // Get parameter and decode URL-encoded string
        $file = urldecode($_REQUEST["file"]); 
       
        // Test whether the file name contains illegal characters
            
        if(preg_match('/^[^.][-a-z0-9_.]+[a-z]$/i', $file)){
            $filepath = "public/" . $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");
        }
    }
    ?>

    
    

Example: The idea is to send the file path information by URL as a parameter to the PHP file downloader.php. Where the file path information will be fed the readfile() function after checking the validity of the file. If an error arises during validation we will display a message saying, “Download cannot be processed”. Let’s create the interface for the user first in a file named index.html.

  • index.html The urlencode() function is used as a security measure to encode the file path in the url.




    <?php
      
    // Array containing sample pdf file names
    $files = array(
        "test1.pdf",
        "test2.pdf"
    );
    $names = array(
        "Book GFG1",
        "Book GFG2"
    );
      
    // 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>';
      
    }
    ?>

    
    

  • Output:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads