Search code examples
phpzipunzipphp-ziparchive

Compressing and extracting a Directory with all its files using PHP


How to compress or zip a directory and then extract alongside with its files and and sub directories using php script.

i have a directory which is needed to be compressed,then transferred to another server and then extracted into a new directory with new name given to it.

PATH.'/'.$TO.'/'.$DIR_WITH_DIR_NAME

Solution

  • First of all if you want to perform zipping and unzipping operations using php it is must to install php zip extension,as i am using Ubuntu as my OS and php7.0 on my server i installed it using this command.

    sudo apt-get install php7.0-zip
    

    For zipping parent directory and other sub directories along side with its files you can use this method given in approved answer.i have used it myself and its best to do so.

    Transfer file using php cURL to other server.Now to unzip a folder in a new folder whichever you are trying to extract files in,first create that directory using this php code.

    @mkdir(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME,0777,true);
    

    This will create the directory and give it all read/write permissions now use this code to extract a directory

    $zip = new ZipArchive;
    if ($zip->open(PATH.'/'.$TO.$COMPRESSED.'/'.$FILE.'.zip') === TRUE) {
    
        if(is_dir(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME)){
        $zip->extractTo(PATH.'/'.$TO.$NEW.'/'.$DIR_WITH_DIR_NAME);
        }
        $zip->close();
        echo 'extracted';
    } else {
        echo 'error in file extracting';
    }
    

    That's it all of the files will be extracted into newly created directory enjoy happy coding.