如何在成功完成下载后让PHP执行一个函数?

I have the feeling this should be quite basic, but I've failed to find a solution anywhere.

I'm working on an application that sends out an email to admins when a file is downloaded. Currently the email is sent out when a download begins, but I need to change this so that it only sends when the download is completed.

I suspect something like PHP's register_shutdown_function might be what I need, but according to the PHP manual shutdown functions are now called before the request is completed. Which leaves me a bit stumped.

For what it's worth, the function that currently handles downloads outputs them like this:

readfile($path);
exit;

The site in question is pretty large and complicated, so ideally I'd like to make as little change to the current code as possible. Any advice on how to solve this problem would be very much appreciated! Thanks.

readfile($path);
mail('admin@example.com', 'Download completed', 'download be done, mon');
exit();

The readfile call will block the script until the file's been loaded and output to the webserver. Note that there is no way for a PHP script to detect if the client has actually successfully downloaded the file. The file itself will be cached partially by the webserver, and PHP's involvement ends when the webserver's cache absorbs the entire file. That means the user can abort the download (or a network glitch kills it), yet you'll still get notified that a download was completed.

readfile() returns the number of bytes read or false if there was an error.

$ret = readfile($path);
if($ret && $ret != 0) {
    // send e-mail
}
exit();