Info_wars
Info_wars

Reputation: 95

Getting a corrupted file whenever i try to download anything using this php script except txt file

Whenever i run this script , i get a corrupted file .Downloading is happening but i get a corrupted file .let it be a zip file ,img file ,only txt files are working good.Plz help

<?php
function download($file){
$file="1.jpg";
$dir = './files/';
$path = $dir.$file;
if(!file_exists($path)){
    die('Error');
}else{
    header('Content-Disposition: attachment; filename='.basename($path));
    header('Content-Type: image/jpeg');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($path));
    readfile($path);

}
}

    download("1.jpg");


?>

Upvotes: 0

Views: 579

Answers (2)

G.Margaritis
G.Margaritis

Reputation: 182

If you are desperately trying to force a file download in php, then you can redirect to the url of your file using:

header("Location: $path");

This method is very frequently used, especially if the file doesn't have a MIME type which is supported by the browser. However, if you do know the MIME type of the file you want to be download, it is strongly recommended that you use the appropriate Content-type header for that purpose.For instance, if you want to force a jpg file download (as in your example) then you will have to use something like this:

header('Content-Disposition: attachment; filename='.basename($path));
header('Content-Type: image/jpeg');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($path));
readfile($path);

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40886

Change

header('Content-Length: ' . filesize($file));

To

header('Content-Length: ' . filesize($path));

You're setting the Content-Length: 0 because instead of passing the full path to filesize() you pass in just the file name. As a result, the browser disconnects without downloading any byte and you get an empty file.

You should also remove these 3 lines

ob_clean();
ob_start();
flush();

Because readfile() alone is sufficient to stream to the browser. There is nothing in the buffer that needs flushing if you've shown us the whole script

Upvotes: 2

Related Questions