PHP Tutorial Tutorials - PHP File Download

PHP File Download

Usually, Downloading Files with PHP is used in Authorized Download Occasion.
Only the authorized user can download the private file.

We can use the PHP readfile() function to read a file and write it to the output buffer ,which force a download directly.

PHP Download File Example

download-list.html

<a href="download.php?file=file1.zip">file1</a>
<a href="download.php?file=file2.zip">file2</a>
<a href="download.php?file=file3.zip">file3</a>

download.php

<?php

if(isset($_REQUEST["file"])){
    $filename = $_REQUEST["file"];
    $file = "images/" . $filename;

    ////////////////////////
    //
    // Usually, in here 
    // Check if user is authorized download the file
    //
    ////////////////////////
    
    // Process download
    if(file_exists($file)) {
        header('Content-Type: application/octet-stream');
        header("Content-Transfer-Encoding: Binary");
        header('Content-Disposition: attachment; filename="'.basename($file).'"');
        header('Expires: 0');
        readfile($file);
        exit;
    }
}
?>

header() is used to send a raw HTTP header.

Date:2019-10-01 03:05:21 From:www.Lautturi.com author:Lautturi