PHP File Download

To download a file in PHP, you need to force the browser to download the file. In this tutorial, we will show you how to download a PHP file from the directory of the server.

With the help of the header() and readfile() function, you can easily download a file in PHP. Also, we are creating a download link by which you can download any file like text, image, pdf, zip, etc.

Suppose, you have a folder called “files\” in your server and you want to download files from that directory.

First, create HTML script to create the download link.

File: php_force_download_file/index.html

<!DOCTYPE>
<html>
<head>
	<h2>How to Force Download File by TutorialsBook</h2>
	<br/>
</head>
<body>
	<a href="download.php?file=tutorialsbook.png"> Download Image File</a><br/>
	<a href="download.php?file=tutorialsbook.txt"> Download Text File</a><br/>
	<a href="download.php?file=LearnPHP.pdf"> Download Pdf File</a>
</body>
</html>

PHP download file link

In the above example, we have created 3 links to download Image, Text, Pdf respectively and we are using one PHP script download.php to download the files from PHP server.

File: 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.';
    }
}
?>

Output

PHP file download

Please get connected & share!

Advertisement