Search code examples
phpdirectoryzipphp-ziparchive

Extracting zip file on host by PHP destroys directory structure


I have a directory structure like this :

members/
  login.php
  register.php

I zip them by PHP ZipArchive in my windows machine, but when I upload it to linux host and extract there by PHP it gives me these as two files with no directory :

members\login.php
members\register.php

I want to have the complete directory structure on the host after unzipping the file. Note that this unpacking code runs without any problem in my local machine. Is it something about windows and linux or what? How can I resolve it?


Solution

  • The problem solved! Here's what I did : I change the code of creating zip file into this function from php.net user comments :

    function addFolderToZip($dir, $zipArchive){
        if (is_dir($dir)) {
            if ($dh = opendir($dir)) {
                //Add the directory
                $zipArchive->addEmptyDir($dir);
                // Loop through all the files
                while (($file = readdir($dh)) !== false) {
                    //If it's a folder, run the function again!
                    if(!is_file($dir . $file)){
                        // Skip parent and root directories
                        if(($file !== ".") && ($file !== "..")){
                            addFolderToZip($dir . $file . "/", $zipArchive);
                        }
                    }else{
                        // Add the files
                        $zipArchive->addFile($dir . $file);
                    }
                }
            }
        }
    }
    $zip = new ZipArchive;
    $zip->open("$modName.zip", ZipArchive::CREATE);
    addFolderToZip("$modName/", $zip);
    $zip->close();
    

    And in the host I wrote just this code to extract the zipped file :

    copy($file["tmp_name"], "module/$file[name]");
    $zip = new ZipArchive;
    if ($zip->open("module/$file[name]") === TRUE) {
        $zip->extractTo('module/');
    }
    $zip->close();
    

    It created the folder and sub-folders. The only bug left is that it extracts every file in all subfolders in the main folder too, so there is two versions of each file in subfolders.