Search code examples
phpunzipfile-renamephp-ziparchive

PHP unzip file into directory, change unzipped folder's name


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.


Solution

  • 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/