当前位置:Gxlcms > PHP教程 > 用php实现文件上载支持断点

用php实现文件上载支持断点

时间:2021-07-01 10:21:17 帮助过:19人阅读

用php实现文件下载支持断点
用php实现文件下载, 同时支持下断点形式
            ob_start();
            $size = filesize($file_dir . $file_name);
            // 输入文件标签
            Header("Content-type: application/octet-stream");
            Header("Cache-Control: must-revalidate, post-check=0, pre-check=0");            
            Header("Content-length: " . $size);
            
            $encoded_filename = urlencode($down_name);
            $encoded_filename = str_replace("+", "%20", $encoded_filename);

            $ua = $_SERVER["HTTP_USER_AGENT"];
            // 处理下载的时候的文件名
            if (preg_match("/MSIE/", $ua)) {
                header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
            } else if (preg_match("/Firefox/", $ua)) {
                header('Content-Disposition: attachment; filename*="utf8\'\'' . $down_name . '"');
            } else {
                header('Content-Disposition: attachment; filename="' . $down_name . '"');
            }
            $fp = fopen($file_dir . $file_name, "r"); // 打开文件

            if (isset($_SERVER['HTTP_RANGE']) && ($_SERVER['HTTP_RANGE'] != "") && preg_match("/^bytes=([0-9]+)-/i", $_SERVER['HTTP_RANGE'], $match) && ($match[1] < $size)) {
                $range = $match[1];                
                fseek($fp, $range);
                header("HTTP/1.1 206 Partial Content");
                //header("Date: " . gmdate("D, d M Y H:i:s") . " GMT");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($file_dir . $file_name)) . " GMT");
                header("Accept-Ranges: bytes");
                $rangesize = ($size - $range) > 0 ? ($size - $range) : 0;
                header("Content-Length:" . $rangesize);
                header("Content-Range: bytes " . $range . '-' . ($size - 1) . "/" . $size);
                // header("Connection: close" . "\n\n" );
                //header("Connection: close"." ");
            } else {                
                header("Content-Length: " . (string) ($size));
                header("Accept-Ranges: bytes");
                $range = 0;
                header("Content-Range: bytes " . $range . '-' . ($size - 1) . "/" . $size);
            }
            fpassthru($fp);
            ob_end_flush();
            fclose($fp);
            exit;

这样就可以支持断点下载了。 希望对用php实现下载的朋友有用

人气教程排行