0

I have a form in which users can select files and create a zip archive of the selected. Everything is working as expected except for the fact that the zip file is created in the wp-admin folder. Instead, I would like for it to be housed in a temp folder and deleted immediately after it has finished downloading.

Here is the PHP code for the creation of the zip archive:

// Creates zip file
function bcg_zip_download() {

    $files = $_POST['checked'];

    $zip = new ZipArchive();
    $zip_name = time().".zip"; // Zip name
    $zip->open($zip_name,  ZipArchive::CREATE);
    $full = wp_upload_dir();
    $base = $full['baseurl'] .'/';

    if (is_array($files)){
        foreach ($files as $file) {
              $path = $file;
              if(file_exists($_SERVER['DOCUMENT_ROOT'].'/bcg/wp-content/uploads/'.$path)){
                  $zip->addFromString(basename($base . $path),  file_get_contents($base . $path)); 
              }
              else {
               echo"file does not exist";
            }
        }
    }

    $zip_file_path = $zip_name;
    $zip->close();
    echo admin_url(). '/' . $zip_name;
    unlink($zip);
    wp_die();
}

add_action( 'wp_ajax_nopriv_download_folder', 'bcg_zip_download' );
add_action( 'wp_ajax_download_folder', 'bcg_zip_download' );
Michelle M.
  • 515
  • 1
  • 7
  • 20

2 Answers2

0

Replace

echo admin_url(). '/' . $zip_name;

to

echo site_url();.'/zip-folder/'.$zip_name;
Ashish Patel
  • 3,551
  • 1
  • 15
  • 31
  • Thank you for this. Unfortunately this won't work since the file is indeed actually being created in the wp-admin folder. I would like for it to be within a tmp folder. – Michelle M. May 13 '17 at 00:05
0

Try changing these lines

$zip_name = time().".zip"; // Zip name
$zip_output_path = get_home_path().'tmp/'.$zip_name; //tmp folder in wordpress root path //rewrite to your need
if (!file_exists(get_home_path().'tmp/')) {
    mkdir(get_home_path().'tmp/', 0777, true);
}
$zip->open($zip_output_path ,  ZipArchive::CREATE);

To delete the files, you may need to write another function to delete them right before you download them. REF http://php.net/manual/en/function.readfile.php OR write a cron to delete them periodically if that suits your application.

rAjA
  • 899
  • 8
  • 13
  • thank you for your answer. However when I change my code to add the above, a file with .html as the extension is being created instead of .zip. – Michelle M. May 13 '17 at 00:04
  • Hey, that's weird as we have $zip_name with '.zip' extension. Were you able to solve this issue? – rAjA May 15 '17 at 07:10