开发者

Site gets unresponsive after file download. What do I do wrong?

I have the code below that i use to download a file from the HDD. The problem I get is that if I stop a download in the middle or after the download ends, the site becomes unresponsive. Any idea why? The environment is LAMP.

.
.
.
// get mime type
if ($dwld_allowed_ext[$fext] == '') {
    $mtype = '';
    // mime type is not set, get from server settings
    if ($file_type == null) {
        if (function_exists('mime_content_type')) {
            $mtype = mime_content_type($file_path);
        }
        else if (function_exists('finfo_file')) {
            $finfo = finfo_open(FILEINFO_MIME); // return mime type
            $mtype = finfo_file($finfo, $file_path);
            finfo_close($finfo);
        }
    }
    else {
        $mtype = $file_type;
    }
    if ($mtype == '') {开发者_开发知识库
        $mtype = "application/force-download";
    }
}
else {
    // get mime type defined by admin
    $mtype = $dwld_allowed_ext[$fext];
}

$asfname = $fname;

// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mtype");
header("Content-Disposition: attachment; filename=\"$asfname\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $fsize);

// download
// @readfile($file_path);
$file = @fopen($file_path,"rb");
if ($file) {
    while(!feof($file)) {
        print(fread($file, 1024*8));
        flush();
        if (connection_status()!=0) {
            @fclose($file);
            die();
        }
    }
    @fclose($file);
}


Call session_write_close() right before sending any download headers.

See this comment:

It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.


Does it become totally unresponsive? Unaccessible to other users? other browsers? I ask because I have a couple of sites where stopping a large page load will hang FireFox for a long time. Other browsers (on the same computer) and other users can still access the site fine. Apparently, in my case, FF is hung but the site is ok.

Edit: After reading your code, it seems a little fishy that your file close command is inside a while loop checking for eof. Try the readfile command to replace that whole file reading thing you're doing: http://us2.php.net/manual/en/function.readfile.php


Try adding exit(); after you print the file (after the last } in the snipped provided). This will stop PHP from parsing the rest of your code which is one reason why you may have the problems you are describing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜