Algorithm for deleting temporary files

I will try to describe the problem. There is 1 script that generates files in the tmp/folder.
After that, immediately the second script starts to give the file to the client (download to the client starts) with support for resuming (http_range), so it is not known when the file will be downloaded.

After that, the file is no longer needed. How to organize the deletion of files and by what criteria? So far, I just came up with the idea of ​​deleting all files in the temporary directory, the lifetime of which is longer than N minutes.

PS: I already tried to figure out how to tell if a file was downloaded at this question.

Answer 1, authority 100%

Perhaps, the option is frostbitten, but if after 10 minutes you can open the file using fopen($file, 'a');– it means that it is not being downloaded at the moment.

Alternatively, make a load handler in which to parse Accept-Range, and do something like this

fseek($f, $acceptRangeStart);
$flock = @fopen('__' . basename($fileToDownload) . $acceptRangeStart, 'w+');
@fclose($flock); //  -
echo fread($f, $acceptRangeBytes);
@unlink('__' . basename($fileToDownload) . $acceptRangeStart);
$finished = true;
foreach (scandir('tmp') as $fn) {
    if (strpos($fn, '__' . basename($fileToDownload)) !== false) {
        $finished = false; //   , 
if ($finished) { //  -  
    unlink($fileToDownload); //   

By the way, why don’t you like the option that is used by almost all file sharing services? (Download link will be available for 24 hours for this computer only)

Answer 2, authority 14%

There is an option when generating a file to write the date and time in its name. Once a day or once an hour (depending on the number of files in the folder), cron scandir() to parse the file name and if the date is less than N minutes / hours / days, delete it

Answer 3, authority 14%

I think this option also has a place to be.

The meaning in general in one function register_shutdown_function()after the work is completed, this function is called and deletes the file that was read.

In my task, it was important to create a temporary file, read the file and delete it immediately after reading, in fact, this option copes with this.

You can also use task queues instead.

 * @param $name
 * @param $content
 * @return string
public static function temporaryFile($name, $content)
        trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR).
        ltrim($name, DIRECTORY_SEPARATOR);
    file_put_contents($file, $content);
        function () use ($file) {
    return $file;