0

When serving files with X-Sendfile, is it possible to have the number of bytes actually sent to the client? Something like this in pseudo code:

header("X-Sendfile: /files/2GB_file.zip");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="2GB_file.zip"');

// don't return here, instead wait until the file is served (or the Range request is served)

$size = get_number_of_bytes_served();

log_to_database($size);

Obviously, we can find this is the Apache log:

example.com:80 1.2.3.4 - - [19/Jun/2018:08:46:30 +0200] "GET /test.txt HTTP/1.0" 200 108893 "-"

(here it's 108893), but it would be useful to have it directly in PHP, immediately once the request is finished. This would avoid having a crontab script that parses the Apache logs periodically, etc. in order to get this information.

Note: I'm using X-Sendfile for performance reason (see Fastest Way to Serve a File Using PHP and Downloading files with download.php).

Basj
  • 41,386
  • 99
  • 383
  • 673
  • You'll have to read the filesize from disk using [filesize](https://www.php.net/manual/en/function.filesize.php) or a similar function – PtrTon Mar 04 '21 at 17:14
  • @PtrTon no because the client might stop in the middle or do a "Range" request (the server will serve only a part of the file). So I want to know the number of bytes actually served. – Basj Mar 04 '21 at 17:23
  • I'm pretty sure PHP 'forwards' the request to apache using the sendfile header. Which means that the PHP process isn't active the entire time the file is being downloaded. As it's not active for the entire time it wouldn't know when it stopped so what amount of bytes were actually served. – PtrTon Mar 04 '21 at 17:28

0 Answers0