2

Is it possible to intercept the unzipping of a directory to change the name of the unzipped folder-to-be?

I'm using the PHP ZipArchive class to do this. The unzipping is working fine, I'd just like to add a timestamp to the unzipped folder's name.

$zip = new ZipArchive;
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    $zip->extractTo($destinationFolder);
    $zip->close();
} else {
    return FALSE;
}

EDIT: to further explain the need, my function is currently overwriting folders of the same name at the point of unzipping. I'm hoping to tack on the timestamp to the new folder to prevent that from happening.

Lauren F
  • 1,282
  • 4
  • 18
  • 29
  • 2
    Have you tried just renaming the folder after it has been successfully unzipped? – amklose Sep 28 '15 at 18:47
  • The problem is that it is overwriting folders with the same name...tacking on the timestamp would prevent that. – Lauren F Sep 28 '15 at 18:56
  • Another option would be to have it unzip into a temporary folder where the contents don't matter and can be overwritten at will, and then move the folder to its final resting place with a new name. - This is generally how file uploads happen on websites so that if the upload is cancelled halfway through, you don't have a bunch of corrupted files floating around. – amklose Sep 28 '15 at 19:03
  • You can use `milliseconds` as the folder name so you end up with a unique `timestamp` – Pedro Lobito Sep 28 '15 at 19:10

1 Answers1

3

I'm assuming that you need to unzip a file to a specific folder with the current date, based on that, you can try:

$zipFile = "test.zip";
$fnNoExt = basename($zipFile, ".zip");
$date = new DateTime();
$now = $date->getTimestamp();
$destinationFolder = "/some/path/$fnNoExt-$now";

$zip = new ZipArchive;
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    if(!is_dir($destinationFolder)){
        mkdir($destinationFolder,  0777);
    }
    $zip->extractTo($destinationFolder);
    $zip->close();
} else {
    return FALSE;
}

It will get the current Timestamp and append it to the folder name, if the folder doesn't exist, creates it and unzip to it.


UPDATE:

I've updated the code so it gets the zipFilename without extension and use it for the new dir name, in this case, it will create a new dir named test-1443467510


NOTE:
Make sure you've write permissions to /some/path/

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • One more question - is it possible to just extract the files from within the zip into this new folder instead of having the unzipped folder nested within the new folder? Right now it's structured as `uploads/new_folder_timestamp/new_folder/files`, but just `uploads/new_folder_timestamp/files` would be ideal. – Lauren F Sep 28 '15 at 20:02