0

I am trying to zip and download files from a directory using PHP and I used suggestion by "skrilled" from the following url:

ZIP all files in directory and download .zip generated

The code works fine for me but I need to add the following functions in the code:

  1. I want to add random characters to the file name as below:

$zipname = 'adcs_RAN-CHARACTERS-HERE.zip';

  1. I want to delete the file after the user downloaded the file.
Community
  • 1
  • 1
Tajik
  • 21
  • 3

1 Answers1

0

I want to add random characters to the file name as below: $zipname = 'adcs_RAN-CHARACTERS-HERE.zip';

When you build the name, go ahead and insert whatever random characters you want. Say for example you wanted to include a somewhat readable timestamp (down to the second), you could do it like this:

$zipname = 'adcs_' . date('YmdHis') . '.zip';

Do note that in the header line you need to include the variable name:

header("Content-Disposition: attachment; filename='$zipname'");

I want to delete the file after the user downloaded the file.

This gets trickier. The problem is you can't know for sure when the user has finished downloading the file. I would use another script to cleanup the files periodically (e.g. scheduled as a cron job). Or each time you are about to create a new zip file, you could delete any old ones first. Or just use the temp/tmp directory on the system which will be cleaned up whenever that happens.

phansen
  • 411
  • 3
  • 7
  • Thank you for the instruction it worked for me. Now I am thinking to add some new functions the the files. 1. How can I track number of downloads using a .txt file or MySQL database? 2. How to display number of downloads on the page? – Tajik Nov 16 '14 at 15:14
  • I would use a MySQL database. Store the uniquely identifiable file name as a field in the table. Whenever a user wants to download a file, check if the file already has an entry in the table, if so you can retrieve and display the current download count. Then when they download the file you can either insert a new record for a new file (starting with a count of 1), or update an existing record by incrementing the download count. – phansen Nov 18 '14 at 02:07