Downloading a file in PHP is such a straightforward process that even a beginner can easily handle it. However, they must have a basic knowledge of the PHP scripts and codes. Normally, we use hyperlinks to open a file on a web browser and it starts downloading automatically.

The automatic file download functionality allows users to download the requested files automatically without rendering them over on the browser first. But how can we automate a file download in PHP?

In this tutorial, we will demonstrate the process and useful PHP codes to automatically download a file in PHP.  This can be possible by using the readfile() and header() functionalities. The tutorial will list down the example PHP codes to automate a file download in PHP. Also, we will provide the PHP script to create a download button. So, let’s get started!

The following sample PHP scripts can be used to automate the file download of any type such as image, text, document, zip, pdf, etc.

How to Create a Download Button in PHP?

First, we start by creating a download button in PHP. The button will allow users to download the files if it doesn’t start downloading automatically. The following sample PHP script can be used to create a download button:

<!DOCTYPE html>




    <meta name="viewport" content=

        "width=device-width, initial-scale=1">


        .btn {

            background-color: limeGreen;

            border: none;

            color: white;

            padding: 12px 30px;

            cursor: pointer;

            font-size: 20px;



        .btn:hover {

            background-color: green;







        <p>Auto width:</p>

        <button class="btn">

            <i class="fa fa-download">Download</i>


        <p>Full width:</p>

        <button class="btn" style="width:100%">

            <i class="fa fa-download">Download</i>





PHP Code to Download a File

After a user clicks on the ‘Download’ button, the code will redirect them to a file named  – downloadFile.php. Now, they can use the file URL and PHP file_get_contents() functionality to download the file.



// Initialize a file URL to 

// the variable 

$url = 



// Use basename() function to 

// return the file  

$file_name = basename($url); 


// Use file_get_contents() function 

// to get the file from url and use 

// file_put_contents() function to 

// save the file by using base name 

if(file_put_contents( $file_name, 

      file_get_contents($url))) { 

    echo "File downloaded successfully"; 

else { 

    echo "File downloading failed."; 



Download the File Through the Anchor Link

In websites and web apps, you have to provide a hyperlink to users to download a file from the server automatically. You can display an HTML link for file download from the directory using the sample code below:


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

PHP Code (download.php)



    // 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 




        echo 'The file does not exist.'; 




Download a file in PHP with a Download Rate Limit

Use the following sample script to set a download rate limit in PHP:


$file_to_download = 'book.pdf';

$client_file = 'mybook.pdf';

$download_rate = 200; // 200Kb/s

$f = null;

try {

if (!file_exists($file_to_download)) {

throw new Exception('File ' . $file_to_download . ' does not exist');


if (!is_file($file_to_download)) {

throw new Exception('File ' . $file_to_download . ' is not valid');


header('Cache-control: private');

header('Content-Type: application/octet-stream');

header('Content-Length: ' . filesize($file_to_download));

header('Content-Disposition: filename=' . $client_file);

// flush the content to the web browser


$f = fopen($file_to_download, 'r');

while (!feof($f)) {

// send the file part to the web browser

print fread($f, round($download_rate * 1024));

// flush the content to the web browser


// sleep one second



} catch (\Throwable $e) {

echo $e->getMessage();

} finally {

if ($f) {





Above, in this tutorial, we have demonstrated the process of automating a file download in PHP. Using the sample codes, scripts, and functionalities, you can get hands-on experience in handling more complex projects than this. So, that’s it in this tutorial! Keep following us and read our latest blogs to learn and master PHP technologies.

Leave a Reply

Your email address will not be published. Required fields are marked *