My Question
I have a script that generates a PDF as a 'one-off'. My script then reads the file and sends it to the browser.
The problem that I have is that I need to delete the file once it has been successfully sent to the browser.
I know that there can be issues with detecting whether or not the user has completely downloaded the file, this being the reason why I am asking this question...
Is there a reliable way to send a file to the browser, and then delete it once it has been fully sent/downloaded to the clients browser/computer?
My Research
I have searched around a lot and can see that this may not be possible. The following questions offered a little information on the topic:
Both these questions seem to contradict each other with one saying you can do it if you use ignore_user_abort
etc, and the other saying that it cannot be done...
I am aware that another potential solution is to simply run a cronjob/scheduled task to delete any files that are over X mins old... I will resort to this as my last option
What I have tried
So far, I have played around with a few things but nothing yet has worked... My code as it stands looks like this:
// Set the headers to PDF
header('Content-type: application/pdf');
// Read the file and send it to the browser
readfile($this->paths['WWW'].'/test.pdf');
// Delete the file
unlink($this->paths['WWW'].'/test.pdf');
UPDATE
I have just re-tested my code and it appears to be working just fine... There was a permissions error on the file so it wasnt deleting when I called unlink
.
However, I am still a little cautious about using this method. Can I be sure that the file will be delivered and then deleted after it has been sent?
I have tested this with a large PDF file and it does work so the above solution may actually be correct. I would still appreciate any other thoughts if anybody wishes to share or can see any hidden issues with this method.