Home >Backend Development >PHP Tutorial >How Can I Force a File Download Using PHP?

How Can I Force a File Download Using PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-24 04:55:14726browse

How Can I Force a File Download Using PHP?

Enforcing File Downloads with PHP

When navigating to a web page, how can we force a file download using PHP?

Solution:

PHP provides a function called readfile() for this purpose. By configuring the headers and utilizing readfile(), we can trigger downloads.

Implementation:

  1. Configure Headers:
    Set the following headers to prompt the download:

    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
    • Content-Type: Specifies the file type (e.g., application/zip for ZIP files).
    • Content-Transfer-Encoding: Ensures binary data is transferred accurately.
    • Content-disposition: Sets the "attachment" option to initiate a download and specifies the file name using the basename() function to extract the file name from the URL.
  2. Use readfile():
    Use readfile() to read the file contents and send them to the browser:

    readfile($file_url); 
  3. Example:
    To download a file named "go.exe" from "http://example.com/go.exe", use the following code:

    $file_url = 'http://example.com/go.exe';
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\""); 
    readfile($file_url); 

Additional Notes:

  • Ensure you set the appropriate Content-Type header based on the file type.
  • Triggering a download with header(location) can result in a halt in execution instead of a page redirect.

The above is the detailed content of How Can I Force a File Download Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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