To download a file in PHP, you need to force the browser to download file except display. In this article, we are going to show how to download a file from directory or server in PHP. Using header()
and readfile()
function, you can easily download a file in PHP. Here we’ll provide the example PHP code to force download file in PHP. Also, this simple PHP script helps to implement a download link which downloads a file from the directory. The following example script can be used for download any types of file like text, image, document, pdf, zip, etc.
Download a File in PHP
$fileName = basename('tcmhack.txt'); $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.'; }
Download a File Through Anchor Link
Sometimes you need to provide a link to the user for download file from the server. 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=tcmhack.png">Dowload File</a>
PHP Code (download.php):
<?php if(!empty($_GET['file'])){ $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.'; } }