我有一个文件下载网站,我通过Laravel提供文件的热链接保护,但似乎下载使我的php进程存活了很长时间(因为一些用户的下载速度很差)。
对于热链接保护,我创建一个会话时,用户进入下载页面,并检查当他们点击下载按钮。
有没有办法做热链接保护,或我可以只是降低内存使用?
这是触发下载的代码:
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);
        }发布于 2018-07-10 13:48:35
您应该按缓冲区大小读取文件(例如2k ),然后发送响应,不要立即发送整个响应,编写如下脚本来下载文件:
    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);https://stackoverflow.com/questions/50909921
复制相似问题