Home > Backend Development > PHP Tutorial > How to Force File Downloads Using PHP Headers and File Handling?

How to Force File Downloads Using PHP Headers and File Handling?

Linda Hamilton
Release: 2024-10-20 20:00:30
Original
673 people have browsed it

How to Force File Downloads Using PHP Headers and File Handling?

Forcing File Downloads in PHP

Allowing users to download images or other files from your website is a common requirement. In PHP, this task can be achieved by leveraging appropriate headers and file handling techniques.

Header Manipulation

To force a file download, we must send appropriate headers to the browser. These headers control browser behavior and instruct it to download the file instead of displaying it in the browser window. Some essential headers include:

<code class="php">header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);  // File size in bytes
header("Content-Disposition: attachment; filename=".$fileName);  // File name to display</code>
Copy after login

File Output

Once the headers are set correctly, we need to output the file itself. This is done using the PHP readfile() function, which reads the file data and sends it to the browser.

<code class="php">readfile ($filePath);                   
exit();</code>
Copy after login

Code Example

Putting it all together, here's an example script that forces an image download in PHP:

<code class="php"><?php
    // Fetch the file info.
    $filePath = '/path/to/file/on/disk.jpg';

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?></code>
Copy after login

Creating a Download Panel

If instead of downloading the file immediately, you prefer a panel to be displayed for user confirmation, you can modify the script slightly. Here's an example:

<code class="html"><a href="download.php?file=/path/to/file.jpg">Download</a></code>
Copy after login

In download.php, you can display a confirmation panel with a button that triggers the actual file download:

<code class="php"><?php
    $file = $_GET['file'];

    if(file_exists($file)) {
        // Display confirmation panel...
        if(isset($_POST['confirm'])) {  // Confirm button clicked
            header("Cache-Control: private");
            header("Content-Type: application/stream");
            header("Content-Length: ".filesize($file));
            header("Content-Disposition: attachment; filename=".basename($file));

            readfile ($file);                   
            exit();
        }
    }
    else {
        die('Invalid file path.');
    }
?></code>
Copy after login

This approach allows you to provide the user with a more user-friendly download mechanism.

The above is the detailed content of How to Force File Downloads Using PHP Headers and File Handling?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template