How to Force Download File in PHP

How to Force Download File in PHP

To download a file in PHP, you have to force the browser to download files except for the display. In this article, we will explain to you how to download a file from a directory or server in PHP. With the help of using header() and readfile() function, you can simply Force Download File in PHP. Here we’ll offer you the sample PHP code to force download files in PHP. Also, this simple PHP script helps to implement a download link that downloads a file from the directory. Therefore, you can use the following example script to download any types of files like text, image, document, pdf, zip, etc.

Download a File in PHP

$fileName = basename('allsweb.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.';
}

SEE ALSO: How to Connect to the Remote MySQL Database using PHP

Download a File Through Anchor Link

Sometimes you have to give a link to the user for download file from the server. Use the following sample code to display an HTML link to download a file from the directory using PHP.

HTML Code:

<a href="download.php?file=allsweb.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.';
    }
}

Also, read our previous blog- Form Validation using jQuery Validation Plugin

Exit mobile version