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:
$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.');
}
Output Headers:
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: ".$fileSize);
header("Content-Disposition: attachment; filename=".$fileName);
Output the File:
readfile ($filePath);
exit();
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3