usnidorg
usnidorg

Reputation: 65

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>

Upvotes: 0

Views: 167

Answers (2)

Igor
Igor

Reputation: 2659

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>";
}

Upvotes: 1

Marc B
Marc B

Reputation: 360672

Have you configured your webserver (Apache in particular) to load mod_xsendfile? Without that module installed, your script essentially does nothing.

Upvotes: 0

Related Questions