php大文件上传及下载

一、大文件上传:

  1. 将php.ini上传文件限制参数放大,最好php7版本,不然大于2G会有问题
file_uploads = On #文件上传需要开启

max_execution_time = 600 # 每个php脚本执行最大时间秒
max_input_time = 600   # 每个php接受数据执行最大时间秒

memory_limit = 300m   #每个PHP页面所吃掉的最大内存
post_max_size = 250m  #接受post数据最大限制
upload_max_filesize =200m  #接受上传文件的最大限制

#要保证这样
memory_limit > post_max_size > upload_max_filesize
  1. 分片上传,使用plupload等组件来实,需要html5浏览器支持,但是合并的时候注意标识按顺序合并
  • 请求接口,服务端创建一个分片上传的“队列”
  • 请求接口,上传文件,指定分片索引 index
  • 所有分片上传完成,请求服务端接口合并文件,依据index顺序。
  1. 共计3处需要修改的地方参考
    nginx,参考
send_timeout    60;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
client_max_body_size 30m;     #这个是关键参数,默认是2m可以全局设置也可以每个网站单独设置

php.ini修改就是上面的地方
php-fpm

request_terminate_timeout  300
request_slowlog_timeout 如果多数为上传大文件则设置较大值,这个根据自身情况设置
  1. nginx支持

二、大文件下载:

  1. 注意:使用readfile函数需要将php.ini的memory_limit设置大点(最好等于参数upload_max_filesize),不能小于下载文件的大小,不然文件下载不动,这种方法需要占用内存,不宜用于大文件和很多人下载使用
    if (!file_exists($file)) {
        echo '文件不存在';
        exit;
    }
    //可重命名为中文
    setlocale(LC_ALL, "zh_CN.GBK");
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
  1. 另外使用nginx的默认自带的XSendfile模块下载,该方法不通过PHP控制,交给nginx来处理 nginx配置,设置protected目录只允许nginx程序访问,防止直接从浏览器直接下载:
#禁止浏览器中访问,仅nginx内部访问(最好做别名alias,不然真实路径被屏蔽,php将无法对真实路径做任何操作,比如:判断文件是否存在、上传文件等等
location /protected/ {
    internal;
    alias $root_path/files/upload/src/
}

php代码

header("X-Accel-Redirect: /protected/test.pdf");

参考:http://www.lovelucy.info/x-sendfile-in-nginx.html

转载于:https://my.oschina.net/kmwzjs/blog/821751

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值