How to download a file in PHP
In PHP, you can download a file from a web server using the header()
function to send the appropriate HTTP headers and the readfile()
or fread()
functions to read and output the file’s content. Here’s a step-by-step guide on how to download a file in PHP:
- Create a PHP script to handle the file download. Let’s call it
download.php
. - Ensure that the file you want to download is located in a directory accessible to your PHP script.
- In your
download.php
script, you can set the appropriate headers to specify the content type, file name, and the content disposition to trigger a file download prompt. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php // File path to the file you want to download $file_path = 'path/to/your/file.pdf'; // Check if the file exists if (file_exists($file_path)) { // Set the appropriate headers for the file download header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . basename($file_path) . '"'); header('Content-Length: ' . filesize($file_path)); // Read and output the file content readfile($file_path); } else { // File not found echo "File not found."; } ?> |
Replace 'path/to/your/file.pdf'
with the actual path to the file you want to download.
- Save the
download.php
script on your web server. - Create a link or a button in your HTML page that points to the
download.php
script. For example:
1 |
<a href="download.php">Download File</a> |
When a user clicks on this link, the download.php
script will be executed, and the file will be prompted for download.
Make sure that you have the necessary permissions and appropriate file paths set up for the file you want to download. Additionally, ensure that the file is within the web server’s document root or is accessible to your PHP script.