How to Trigger Automatic File Downloads in PHP
Question:
How to implement a functionality in PHP that automatically prompts users to download a file to their local machine when they click on a web link? This is commonly seen on download sites where users can save software files to their disks upon clicking.
Answer:
To achieve this behavior, you need to send specific headers before outputting the file in PHP:
header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); header("Content-Type: application/octet-stream"); header("Content-Length: " . filesize($File)); header("Connection: close");
The Content-Disposition header specifies that the browser should prompt the user to save the file with the provided filename.
The Content-Type header indicates that the file should be treated as a generic binary stream, which most browsers recognize as a downloadable file.
The Content-Length header sets the size of the file being downloaded.
Finally, the Connection: close header instructs the browser to close the connection after the download completes.
Additional Notes:
The above is the detailed content of How to Automatically Trigger File Downloads in PHP?. For more information, please follow other related articles on the PHP Chinese website!