Improving efficiency of download code
Since the code is only reading the contents of the file to see if there are contents in the file, an optimization for both speed and memory usage would be to use the filesize() function and not read the contents. Reading the contents of the file consumes both time and memory.
Rather than writing the contents read in, copy or move the original file to the new location using either rename() or move_uploaded_file().