I am using php to download a file and I want the file should get delete automatically from the server after successful completion of download. I am using this code in php.
$fullPath = 'folder_name/download.txt';
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
$fd = fopen ($fullPath, "r");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
fclose ($fd);
}
unlink($fullPath);
You can see in the code after download I am unlink the file. But if I do so corrupted file is getting downloaded. Because sometime the file getting deleted before it get download fully. Is there anyway in php to know that client download the file successfully then I can delete it? Any idea will be highly appreciated.
If you really are downloading (instead of uploading, like code in your posts suggests), you might be interested in tmpfile function that is specifically designed to create files, that will be immediately removed on having its descriptors closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With