henryspace

记录精彩的程序人生 开始使用

PHP 使用 header 下载文件

$sql = ";";

$fileName = date('Y_m_d', $unixTime) . 'debuglog.sql';
$file_path = ROOT_PATH . 'public/uploads/'.$fileName;

file_put_contents($file_path, $sql);

//判断路径是否存在
if(!file_exists($file_path)){
    echo "文件不存在";
    return;
}

$fp = fopen ($file_path, "rb");    // 文件以二进制形式打开
$ua = $_SERVER["HTTP_USER_AGENT"];

//取得文件信息
$file_size = filesize($file_path);
$file_name = basename($file_path);
$encoded_file_name = urlencode($file_name);
$encoded_file_name = str_replace("+", "%20", $encoded_file_name);

header('Content-Type: application/octet-stream;charset=utf-8');
header("Accept-Ranges:bytes");
header("Accept-Length:".$file_size);

// 兼容多浏览器下载
if (preg_match("/MSIE/", $ua)) {
    header('Content-Disposition: attachment; filename=' . $encoded_file_name);
} else if (preg_match("/Firefox/", $ua)) {
    header('Content-Disposition: attachment; filename*=utf8\'\'' . $file_name);
} else {
    header('Content-Disposition: attachment; filename=' . $file_name);
}

// 清除缓存很重要
ob_clean();
flush();
// 清除缓存很重要

$buffer = 1024;
$buffer_count = 0;

while (!feof($fp) && $file_size - $buffer_count > 0) {
    $data = fread($fp, $buffer);
    $buffer_count += $buffer;
    echo $data;
}

fclose($fp);

unlink($file_path);

exit();
请成为永远疯狂永远浪漫永远清澈的存在。

评论
留下你的脚步
推荐阅读