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!