Home > Backend Development > PHP Tutorial > How Can PHP Automatically Trigger File Downloads?

How Can PHP Automatically Trigger File Downloads?

Patricia Arquette
Release: 2024-11-17 18:23:02
Original
509 people have browsed it

How Can PHP Automatically Trigger File Downloads?

Automatically Triggering File Downloads in PHP

Introduction:
Downloading files upon visiting specific web links is a common practice on download sites. PHP provides the functionality to achieve this behavior, offering an effortless way for users to save files to their local systems.

PHP Code for Automatic Downloads:
To initiate an automatic download, add the following headers prior to outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");
Copy after login

Explanation:

  • Content-Disposition: Specifies the disposition of the content as an attachment and sets the file's name using basename($File) to obtain the filename.
  • Content-Type: Declares the MIME type as application/octet-stream, indicating that the file is a binary stream.
  • Content-Length: Sets the file size in bytes, allowing the browser to display the download progress.
  • Connection: Sets the connection to be closed immediately after the download is complete.

Additional Note:

  • The basename($File) function extracts the filename from the path, ensuring that it is displayed correctly in the browser's download prompt.
  • An alternative MIME type, application/force-download, can also be used to trigger automatic downloads, although application/octet-stream is widely supported.

The above is the detailed content of How Can PHP Automatically Trigger File Downloads?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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