首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Laravel下载响应,具有热链接保护和低内存使用率

Laravel下载响应,具有热链接保护和低内存使用率
EN

Stack Overflow用户
提问于 2018-06-18 12:48:27
回答 4查看 1.4K关注 0票数 3

我有一个文件下载网站,我通过Laravel提供文件的热链接保护,但似乎下载使我的php进程存活了很长时间(因为一些用户的下载速度很差)。

对于热链接保护,我创建一个会话时,用户进入下载页面,并检查当他们点击下载按钮。

有没有办法做热链接保护,或我可以只是降低内存使用?

这是触发下载的代码:

代码语言:javascript
运行
复制
if($request->session()->get('file') == $apk->generated_filename) 
        {   
            $headers = array
            (
                'Content-Type' => 'application/vnd.android.package-archive'
            );
            Apk::find($apk->id)->increment('downloads_co');
            return response()->download(config('custom.storage') . $apk->generated_filename, $apk->filename, $headers);
        }
EN

Stack Overflow用户

发布于 2018-07-10 13:48:35

您应该按缓冲区大小读取文件(例如2k ),然后发送响应,不要立即发送整个响应,编写如下脚本来下载文件:

代码语言:javascript
运行
复制
    ignore_user_abort(true);
    set_time_limit(0); \

    $path = "/absolute_path_to_your_files/"; // change the path to fit your websites document structure

    $dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\).]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
    $dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
    $fullPath = $path.$dl_file;

    if ($fd = fopen ($fullPath, "r")) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath);
        $ext = strtolower($path_parts["extension"]);
        switch ($ext) {
            case "pdf":
                header("Content-type: application/pdf");
                header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
                break;
            // add more headers for other content types here
            default;
                header("Content-type: application/octet-stream");
                header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
                break;
        }
        header("Content-length: $fsize");
        header("Cache-control: private"); //use this to open files directly
        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }
    fclose ($fd);
票数 1
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50909921

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档