Forum Moderators: coopster
I've got a new service on a website which involves dynamically creating a binary file (which is an installation package) for a user to download.
I want to then clean-up by deleting the file after it's been downloaded.
Problem is while it's being downloaded I can't delete it.
I'm sure I'm not the first person to come up against this. Anyone have some thought as to the best method to achieve the desired result? I can think of three ways:-
1. Have the PHP script that served the download block by trying to get an FLOCK on the file. Then delete.
2. Use outbound buffering to serve the file from memory, having deleted it from disk first.
3. Use a CRON job to clean up disk files every 5 mins or so
Problem with 1 and 3 is they just "feel" like an ugly hack to me. Problem with 2 is the downloaded file can be up to 18mb in size, so could eat up RAM quite quicky.
Pseudo code looks something like this:-
click_me_to_download.php
// Build the application
$path = buildPersonalCopyOfMegaApp($username from a cookie);
// Ship it to client
readfile($path);
// Delete the file from disk
deletefile($path); <-- fails as we need to wait for the download to finish
Any thoughts?
Thanks!
$file = fopen($file_path,"rb");
if ($file) {
while(!feof($file)) {
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
fclose($file);
break;
}
}
fclose($file);
}
<?php
$pathtooriginal = $_SERVER['DOCUMENT_ROOT'].'/play/download-delete/original.tif';
$pathtoduplicate = $_SERVER['DOCUMENT_ROOT'].'/play/download-delete/'.uniqid().'.tif';
copy($pathtooriginal, $pathtoduplicate);
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($pathtoduplicate));
header('Content-Disposition: attachment; filename=' . basename($pathtoduplicate));
readfile($pathtoduplicate);
unlink($pathtoduplicate); // doesn't execute until readfile() is finished
?>
Of course, my test was over a LAN, so perhaps this would fail if the download speed was slower?