文件下载器下载0字节的文件在PHP


file downloader downloading 0 BYTE file in PHP

我的代码并不总是工作。大多数时候它下载0字节映像。我可以通过这段代码下载特定的图像,这段代码可以通过它的名字保存图像的大小。如果我重命名图像,它将下载0 BYTE。

$file_path= $full_path;
$file = pathinfo($file_path);
$base = $file['basename'];
$dir = $file['dirname'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=".$base);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: no-cache');
header('Content-Length: ' . filesize($base));
ob_clean();
flush();
$path = $dir."/".$base;
readfile($path);
exit;

这段代码修复了我的问题....

function download($path)
{
// if file is not readable or not exists
if (!is_readable($path))
    die('File does not exist or it is not readable!');
// get file's pathinfo
$pathinfo = pathinfo($path);
// set file name
$file_name = $pathinfo['basename'];
    $mime = 'application/octet-stream';
// set headers
header('Pragma: public');
header('Expires: -1');
header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
header('Content-Transfer-Encoding: binary');
header("Content-Disposition: attachment; filename='"$file_name'"");
header('Content-Length: ' . filesize($path));
header("Content-Type: $mime");
// read file as chunk to reduce memory usages
if ( $fp = fopen($path, 'rb') ) {
    ob_end_clean();
    while( !feof($fp) and (connection_status()==0) ) {
        print(fread($fp, 8192));
        flush();
    }
    @fclose($fp);
    exit;
}

}

download($file_path);