Force File Download in PHP
To provide a download link for a file in PHP, you can use the following steps:
Retrieve the File Information:
<code class="php">$filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); } else { die('The provided file path is not valid.'); }</code>
Output Headers:
<code class="php">header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName);</code>
Output the File:
<code class="php">readfile ($filePath); exit();</code>
Note: Be cautious if implementing this in a function to allow downloads of arbitrary files, as you need to prevent directory traversal and restrict downloads to a defined area.
The above is the detailed content of How to Force File Download in PHP?. For more information, please follow other related articles on the PHP Chinese website!