简体   繁体   中英

Move Zipped Folder from PHP Server to Client

I am using Wordpress. I have created a form in which users check which files to be included in a zipped folder and the folder containing the files is created on the server.

My question is how do I move this newly created zipped folder to the client? I would like the user to be able to select where on the client the folder is downloaded as well.

HTML

<form method="post">
    <input type="checkbox" name="checked[]" value="<?php echo $path; ?>">
    <input type="submit" name="download" value="Download Selected">
</form>

PHP

if(isset( $_POST['download'] ) && !empty($_POST['checked']) ){
$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 ($_POST['checked'] as $file) {

          echo $full_path = $file;
          echo $_SERVER['DOCUMENT_ROOT'] . $full_path;
          if(file_exists($_SERVER['DOCUMENT_ROOT'].'/bcg/wp-content/uploads/'.$full_path)){
              $zip->addFromString(basename($base . $full_path),  file_get_contents($base . $full_path)); 
              echo 'file exists'; 
              bcg_download_function($zip_name);
          }
          else{
           echo"file does not exist";
          }
        }

        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename='.$zip_name);
        header('Content-Length: ' . filesize($zip_name));
        readfile($zip_name);
        $zip->close();
    }
}

You need to use ajax technology.

  1. Rename your input type="submit" to input type="button"

  2. Intercept click on this button in your js code

  3. On click, post ajax request from browser to your server

  4. In ajax processing function, use php code shown here, form and return a link to newly created zip

  5. In your js code, in ajax success function, get this link and show it to the user.

You can read detailed manual how to use ajax in WordPress here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM