如何确定通过http发送的字节数

时间:2009-11-09 09:22:53

标签: php download

我需要知道如何确定通过http发送的字节数。

这是我到目前为止所做的。


ignore_user_abort(true);

header('Content-Type: application/octet-stream; name="file.pdf"');
header('Content-Disposition: attachment; filename="file.pdf"');
header('Accept-Ranges: bytes');
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-transfer-encoding: binary');
header('Content-length: ' . filesize('file/test.pdf'));
readfile('file/test.pdf');

    if (connection_aborted()) {
        $transfer_success = false;
        $bytes_transferred = ftell($handle);
        echo $bytes_transferred;
        die();
    }

任何人都可以帮助我吗?

由于

2 个答案:

答案 0 :(得分:1)

看一下同一个问题的另一篇文章:

PHP - determine how many bytes sent over http

从链接页面获取的代码示例(最初由J.发布,经过修改以符合您的示例):

ignore_user_abort(true);

$file_path = 'file/test.pdf';
$file_name = 'test.pdf';

header('Content-Type: application/octet-stream; name=' . $file_name );
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Accept-Ranges: bytes');
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-transfer-encoding: binary');
header('Content-length: ' . $file_path);

$handle = fopen($file_path, 'r');
while ( ! feof($handle)) {
    echo fread($handle, 4096);
    if (connection_aborted()) {
        $transfer_success = false;
        $bytes_transferred = ftell($handle);
        break;
    }
}
fclose($handle);

答案 1 :(得分:0)

尝试使用readfile的返回值:

$bytes_transferred = readfile('file/test.pdf');
$transfer_success = ($bytes_transfered == filesize('file/test.pdf'));
if (!$transfer_success) {
    // download incomplete
}