Forcing File Downloads in PHP
Allowing users to download images or other files from your website is a common requirement. In PHP, this task can be achieved by leveraging appropriate headers and file handling techniques.
Header Manipulation
To force a file download, we must send appropriate headers to the browser. These headers control browser behavior and instruct it to download the file instead of displaying it in the browser window. Some essential headers include:
<code class="php">header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); // File size in bytes header("Content-Disposition: attachment; filename=".$fileName); // File name to display</code>
File Output
Once the headers are set correctly, we need to output the file itself. This is done using the PHP readfile() function, which reads the file data and sends it to the browser.
<code class="php">readfile ($filePath); exit();</code>
Code Example
Putting it all together, here's an example script that forces an image download in PHP:
<code class="php"><?php // Fetch the file info. $filePath = '/path/to/file/on/disk.jpg'; if(file_exists($filePath)) { $fileName = basename($filePath); $fileSize = filesize($filePath); // Output headers. header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".$fileSize); header("Content-Disposition: attachment; filename=".$fileName); // Output file. readfile ($filePath); exit(); } else { die('The provided file path is not valid.'); } ?></code>
Creating a Download Panel
If instead of downloading the file immediately, you prefer a panel to be displayed for user confirmation, you can modify the script slightly. Here's an example:
<code class="html"><a href="download.php?file=/path/to/file.jpg">Download</a></code>
In download.php, you can display a confirmation panel with a button that triggers the actual file download:
<code class="php"><?php $file = $_GET['file']; if(file_exists($file)) { // Display confirmation panel... if(isset($_POST['confirm'])) { // Confirm button clicked header("Cache-Control: private"); header("Content-Type: application/stream"); header("Content-Length: ".filesize($file)); header("Content-Disposition: attachment; filename=".basename($file)); readfile ($file); exit(); } } else { die('Invalid file path.'); } ?></code>
This approach allows you to provide the user with a more user-friendly download mechanism.
The above is the detailed content of How to Force File Downloads Using PHP Headers and File Handling?. For more information, please follow other related articles on the PHP Chinese website!