php文件下载的原理
- 利用浏览器请求返回未知格式时,就采用下载的方式
- php内部通过header 模拟请求,输出文件
还有一个MIME类型的知识点 :传送门
heard 知识点: https://www.cnblogs.com/hellozg/p/9268131.html
在只用使用文件下载首先要确定fileInfo开启:
开启步骤:php扩展设置——》php扩展——》php_fileinfo 在这前面打勾
function_exists('file_info') :函数可以用来验证一个php扩展是否开启
代码:
<?php
$file = "upload/123.jpg";
// 获文件的mime的类型
$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($fileinfo, $file);
finfo_close($fileinfo);
//发送指定文件的mime
header('Content-Type:' . $mimeType);
//指定下载文件的描述
header('Content-Disposition: attachment; filename=' . basename($file));
$fileSize = filesize($file);//坑 filesize 如果超过2G 低版本php会返回负数
header('Content-Length:' . $fileSize); //注意是'Content-Length:' 非Accept-Length
//输出到浏览器
readfile($file);
?>