Search code examples
phpdownloadx-sendfile

Protecting Downloads


I was just testing this download script below. The downloading works fine but the downloaded zip or rar archive is always corrupt and cannot be opened. I tested it on local development server as well as my hosting account.

I am just trying to learn how this works but I don't really understand it.

All help is appreciated!

Test Code:

<?php
$is_logged_in = 1;
$path_to_file = 'downloads/tes.zip';
$file_name = 'test.zip';

if ($is_logged_in == 1)
{
    header("X-Sendfile: $path_to_file");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$file_name\"");
    exit;
}
?>

<h1>Permission denied</h1>
<p>Please Login first!</p>

Solution

  • It mostly probable that you have something appended/prepended to the file. Try to use buffering and cleaning.

    <?php
    ob_start();
    $is_logged_in = 1;
    $path_to_file = 'downloads/tes.zip';
    $file_name = 'test.zip';
    
    if ($is_logged_in == 1)
    {
        $fp = fopen($path_to_file, 'rb');
    
        if(is_resource($fp))
        {
                ob_clean();
                header("Content-Type: application/force-download");
                header("Content-Length: " . filesize($path_to_file));
                header("Cache-Control: max_age=0");
                header("Content-Disposition: attachment; filename=\"$file_name\"");
                header("Pragma: public");
                fpassthru($fp);
                die;
        }
    } else {
        echo "<h1>Permission denied</h1>";
        echo "<p>Please Login first!</p>";
    }