Download File in PHP

File Download System is the most important feature of any website. Do you want to know how to download file in PHP?

In this article, You will learn how to secure download file in PHP?

Before start this tutorial, Make sure that PHP is configured to allow file uploads. Any php web server configured with default values set in php.ini file. In your “php.ini” file, search for file_uploads text, and ensure this value is on:

file_uploads = On


If you want to upload file in PHP, Please read the following articles:

How to Upload File in PHP


Now Let’s Developing Script to File Download in PHP

File Download In PHP

Now we develop a php script for download files. First, create a file called download.php and enter the following code:

    // Decode URL-encoded string
    $file = urldecode($_REQUEST["file"]); 
    // File Path
    $filepath = "upload/" . $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

Then we request download.php for the file download. If requested file exists on upload directory, Download will start automatically.  An Example:

<a href="download.php?file=file.jpg">Download file</a>



Please enter your comment!
Please enter your name here