Reputation: 15949
I have this dilemma many times - and I would like one time and for all adjust the answer in my head .
While creating files with PHP , like *.zip , *pdf or any other , PHP will give you two operational options :
write to disk.
stream with headers to direct download.
things to consider are :
A practical example :
Let´s say that I have a website to download a packed zip with images .
If I stream the zip - it will obviously cost CPU (and time ).
If I write to disk - it can be security problem (assuming someone can "crawl" the site , find the zip folder or files somehow, and bulk download all)
If I write to disk , I will also need to check somehow if the files inside the zip should be updated or not , Plus I will have to verify the file´s integrity .
Anyhow - I would like to hear what people has to say about which one is the preferred method under which circumstances , what are best practices for this , or any other insight .
Upvotes: 0
Views: 177
Reputation: 522024
Security is of no concern if you do it right. Just don't store the files inside the public webroot, or otherwise configure your web server to not serve these files directly.
With that out of the way, it depends on what you want. If you need to serve the same zip again and again, of course it makes sense to zip it once and write it to disk, from where you will serve it the next time. That's a simple caching strategy.
If you need to make sure you have the latest version of the zip, make a hash of the contents in some fashion. For example:
(foo.txt, bar.jpg, baz.doc)
$hash = md5(foo.txt, bar.jpg, baz.doc)
$hash.zip
doesn't already exist, create it$hash.zip
That's a typical caching strategy to avoid doing costly operations again and again.
Upvotes: 1
Reputation: 526573
If the same identical zip file is going to be downloaded multiple times, it makes sense to cache it (on disk or some other persistent storage). If you include a hash of the zip's contents as part of the file name (or whatever identifier you cache the data under), then it's trivial to see if your cached value matches what you want to serve.
If any given zip file is going to be downloaded only once, then it makes more sense to just stream it directly.
Upvotes: 1