6

Is it possible in PHP to get a count of the number of bytes transmitted to the client? For example, if I'm outputting a 10 MB file, is there a way to find out if all 10 MB were sent to the client, or to see if the client interrupted the transfer partway? I know Apache will log this afterwards, but I'd like to access the data in PHP.

Jay
  • 2,123
  • 1
  • 22
  • 29
  • you want to make a progressbar or something like that? – Natrium Oct 02 '09 at 06:34
  • i just wanted to mark files as completely downloaded, then remove them from a list. the problem was file_get_contents(), it doesn't catch the user interruption. if you use fread() and loop through, you can catch it, and then use ftell() to figure out roughly how many bytes were sent. (sorry for posting the question when i ended up figuring it out on my own) – Jay Oct 02 '09 at 06:52

2 Answers2

13

Take a look at the ignore_user_abort and connection_abort function.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
11

Here's what I ended up doing (thanks Gumbo):

ignore_user_abort(true);

$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);
Jay
  • 2,123
  • 1
  • 22
  • 29