perlunlink

Why unlink in Perl deletes the file before displaying it although I call unlike after


Image file deleted after display, not before.

I upload a file using Perl's file upload. The upload works fine, it is is the intended upload directory. In the same script, I display the file (it is an image file) and that works ok too. What I want to do is to delete the file after I show it, but when I do that I get a broken link and the image is (of course) deleted from the directory. Tried the sleep function in between to no avail.

print "<img src=\"path_to\image\">
#sleep (5);
unlink "path\to\image\";

Solution

  • When you print the web page and it gets sent to the client, that can take a few seconds, especially if you send a lot more content after the link. But your code just deletes the file, hence when the browser renders the page and tries to display the image, it's already gone.

    Your sleep slows down the page rendering as well, so that really may or may not help you, depending on buffering it may just make the whole page slower to load.

    The real solution here would be to have another mechanism clean up such image files, e.g., delete all files at midnight, or check every hour and delete each file that has been created x minutes ago.