How should the temporary file be saved when creating and download zip file using PHP?
I wish to zip a directory on the server and download it to the user. I've found great information on this site on how to zip the directory.
The part that has me stumped is where to store the temporary file. From what I've read, zipArchive requires that the zip file be saved on the server, and I can't download it without saving it. Correct?
I've seen solutions where they recommend saving it as "somename.zip", and then using readfile() along with the appropriate headers to download, and then using unlink() after the download to get rid of it. But where to store "somename.zip" and what if there are collisions?
So, then I started thinking that I should create a file with a random name in some temporary directory. Or maybe I should use something like tmpfile(), but that returns a file handler and I don't know how that will work with zipArchive.
For my application, the size of the directory is fairly small, and would like to not even write it to disk, but to memory instead. Maybe something like $tmp_handle = fopen('php://temp', 'r+');, but again this returns a file handler and I don't know how that will work with zipArchive.
How should the zip file created by zipArchive be temporary saved?
As ZipArchive class works with stacked streams, the $filename parameter cannot be php://temp or php://memory. It has to be a 'real' filepath on the filesystem.
Some lines of thought :
As said in a comment, tempnam() function can help you to avoid temporary files names collisions. I think storing the file temporarily and readfile()'ing it is the most common and not a bad option
If you absolutely want that temporary file be stored in memory, you can mount a tmpfs directory on your Linux system. It will be seen as a 'normal' directory for PHP but will be stored in RAM
If you can use shell_exec() function, you can zip the directory in a command line and read the output in PHP : it will be stored in memory.
In my opinion, the first option (your first idea) is better in most cases, because :
allowing the use of shell_exec() can be dangerous
if one day you have big files to zip, this could fill the memory, resulting in very poor performance