Current Location: Home> Latest Articles> Implement the download button: the front-end triggers the request, and the back-end uses header() to push the file

Implement the download button: the front-end triggers the request, and the back-end uses header() to push the file

M66 2025-06-05

File download is one of the common requirements in web applications. Through PHP's header() function, you can push files to the browser and trigger the user's file download operation. This article will introduce in detail how to implement file download function through PHP's header() function, and explain how the front-end triggers requests and how the back-end uses the header() function to push files to the browser.

How to trigger file download request in front-end?

In the front-end, we can use HTML or JavaScript to trigger file download requests. The easiest way is to trigger the download by clicking on a link. Usually, we use the a tag to define a link and use href to specify the URL of the file.

 <a href="http://m66.net/download.php?file=example.txt" download>Click to download the file</a>

In this example, after the user clicks on the link, the browser will request the download.php file and pass the file parameters (such as file=example.txt ) to the backend PHP script via GET request.

In addition, you can also dynamically trigger file downloads through JavaScript, such as:

 function downloadFile() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://m66.net/download.php?file=example.txt", true);
    xhr.responseType = "blob"; // Indicates that the returned data is a binary file
    xhr.onload = function() {
        const blob = xhr.response;
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = 'example.txt'; // Set the downloaded file name
        link.click(); // Trigger click,Download the file
    };
    xhr.send();
}

This JavaScript requests the file through Ajax and uses the Blob object to create a file download link, which will then automatically trigger the download.

How to push files using header() in the backend?

In PHP, the header() function is used to send raw HTTP header information. Through the header() function, we can tell the browser to download a file. The specific operations are as follows:

  1. First, make sure you have verified the existence of the file.

  2. Set the appropriate Content-Type and Content-Disposition headers to tell the browser how to handle the file.

  3. Use readfile() or other methods to output the file content to the browser.

 <?php
// download.php

// Get file name parameters
$file = isset($_GET['file']) ? $_GET['file'] : '';
$filePath = '/path/to/files/' . $file; // Set the absolute path to the file

// Check if the file exists
if (file_exists($filePath)) {
    // Set the response header,告知浏览器Download the file
    header('Content-Type: application/octet-stream');  // Applicable to all file types
    header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');  // Force download and specify file name
    header('Content-Length: ' . filesize($filePath)); // File size
    header('Cache-Control: no-cache, no-store, must-revalidate'); // Disable cache
    header('Pragma: no-cache');
    header('Expires: 0');

    // Output file content
    readfile($filePath);
    exit;
} else {
    echo 'File does not exist or path is wrong!';
}
?>

In this PHP example, we first get the file parameters passed in the URL (for example.txt ) and then look up the file by the file path. If the file exists, we set the file download type and other information through header() , and then use readfile() to output the file contents, and finally realize the download of the file.

Code parsing:

  • header('Content-Type: application/octet-stream') : Set the file type to a binary stream. For all types of files, use application/octet-stream as the general MIME type.

  • header('Content-Disposition: attachment; filename="filename"') : Set the browser to download the file as an attachment when receiving the response, and assign a file name to the file. The file name can be obtained through basename() .

  • header('Content-Length: ' . filesize($filePath)) : Sets the file size. This is especially important for large files, and browsers can estimate download progress based on this information.

  • readfile($filePath) : This function will read the file and output it directly to the browser.

  • exit; : After outputting the file content, call exit; terminates the script execution to avoid unnecessary output or response.

Summarize

By using PHP's header() function and combined with appropriate HTTP header settings, the file download function can be implemented. In the front end, the user requests the file by clicking on the link or triggering an Ajax request; in the back end, PHP sets the correct response header through the header() function, and then pushes the file content to the browser for download. In this way, you can easily add file download functionality to your web application.