简体   繁体   中英

Zip File - Download - Then Unzip

I'm getting really confused here. So here's whats going on in my project. The user clicks download then select directory to save the file, the file will be a zip file. After that I want to extract that zip file in the same directory the users chooses. Is this even possible in one script?

Here is my php code

<?php 
require_once('connect.php');
// Get real path for our folder
$rootPath = realpath($_GET['uniq']);

// Name of the zip derive from the database
$zipname = $_GET['name'] . '.zip';
// Initialize archive object
$zip = new ZipArchive();
$zip->open($zipname, ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }   
}

// Zip archive will be created only after closing object
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
?>

If its not possible another question. Is it possible to let user choose a zip file then after that it will be extracted at some client directory ie. C://xamp/extracthere/ using javascript.

Once the user has downloaded the file to their machine, it's beyond your control. You can't force them to unzip it, or do anything else with it for that matter.

Imagine if you could control the files on a user's local disk, it would be a hacker's dream. This is impossible using both PHP and JavaScript, for similar reasons in each case.

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