Code Solution for Sending a File to the Client for Download
<?php
// Get the file path from the request parameter
$filePath = $_GET['file_path'];
// Check if the file exists
if (!file_exists($filePath)) {
header("HTTP/1.0 404 Not Found");
exit;
}
// Get the file size
$fileSize = filesize($filePath);
// Set the appropriate headers
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($filePath) . "\"");
header("Content-Length: $fileSize");
// Output the file content
readfile($filePath);
?>
How it works
- The code first checks if the file exists. The
file_exists()
function is used for this purpose. If the file does not exist, it sets the HTTP status code to 404 and exits the script.
- Next, it gets the file size using the
filesize()
function. This is necessary for setting the Content-Length
header.
- It then sets the appropriate headers for the file download:
Content-Type: application/octet-stream
: This sets the content type to octet-stream, which indicates that the content is a binary file.
Content-Disposition: attachment; filename="filename.txt"
: This sets the content disposition to attachment and specifies the filename of the downloaded file.
Content-Length: $fileSize
: This sets the content length to the size of the file in bytes.
- Finally, it outputs the file content using the
readfile()
function.
How to implement it effectively
- Make sure that the file path is passed as a parameter to the script. You can do this using the
$_GET
or $_POST
global variables.
- Check for file existence before attempting to download it.
- Set the appropriate headers for the file download. This is important to ensure that the browser correctly handles the downloaded file.
- Use the
readfile()
function to output the file content. This is the most efficient way to download a file in PHP.