How to force a file to get downloaded in PHP?

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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");
        }
    }
    ?>

    chevron_right

    
    

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.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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>';
      
    }
    ?>

    chevron_right

    
    

  • Output:



My Personal Notes arrow_drop_up

Always a learner

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.