How to Force Download File Using PHP 2023
Typically you can use a hyperlink to open a file in a browser. In this case, the file can be downloaded manually via the browser. If you want to dynamically download a file and automatically save it to your local drive, force the browser to download the file instead of displaying it. The Forced Download feature allows the user to download file in PHP, where the required files are forcibly downloaded without rendering in the browser. In this tutorial we will show you how to download a file from a directory or server in PHP.
How to Download file from folder in PHP
You can easily load a file in PHP using the header() function and the readfile() function. Here we provide a sample PHP code to force download a file in PHP. Additionally, this simple PHP script will help you implement a download link that downloads a file from a directory. The following sample script can be used to upload any file type such as text, image, document, PDF, ZIP, etc.
See also
- Convert HTML to PDF in PHP using Dompdf
- Import Excel File into MySQL Database in PHP using Spreadsheet
- How to Export excel data from Database in PHP using Spreadsheet
Download File in PHP
<?php
// Define file name and path
$fileName = 'certificate.pdf';
$filePath = 'uploads/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
Download File Through Anchor Link
In the web application, you need to provide a hyperlink to allow the user to download files from the server dynamically. Use the below sample code to display an HTML link to download a file from the directory using PHP.
HTML Code:
<a href="download.php?file=certificate.pdf">Download File</a>
PHP Code (download.php):
<?php
if(!empty($_GET['file'])){
// Define file name and path
$fileName = basename($_GET['file']);
$filePath = 'files/'.$fileName;
if(!empty($fileName) && file_exists($filePath)){
// Define headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file
readfile($filePath);
exit;
}else{
echo 'The file does not exist.';
}
}
?>