Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete file from the server after download in php

Tags:

php

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.

like image 756
Amar Banerjee Avatar asked Jun 26 '13 12:06

Amar Banerjee


1 Answers

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.

like image 163
rr- Avatar answered Oct 26 '22 02:10

rr-