每当我尝试使用此PHP脚本除txt文件下载任何内容时获取损坏的文件

每当我尝试使用此PHP脚本除txt文件下载任何内容时获取损坏的文件

问题描述:

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


?>

每当我运行此脚本时,我都会收到一个损坏的文件.Downloading正在发生,但我收到一个损坏的文件.let it 是一个zip文件,img文件,只有txt文件正常工作.Plz帮助 p>

 &lt;?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); 
 
} 
} 
 
下载(“1.jpg”)  ; 
 
 
?&gt; 
  code>  pre> 
  div>

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);

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