Search code examples
phpunzip

how to prevent extracting a php file from zip


i am using this piece of code to unzip a .zip file

$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
   $zip->extractTo('/my/destination/dir/');
   $zip->close();
   echo 'ok';
} else {
   echo 'failed';
}

Lets say: there is a .php file in the .zip and i do not want a .php file to be extracted. How can i prevent that?


Solution

  • You can try something like this for PHP >= 5.5:

    $zip = new ZipArchive;
    if ($zip->open('test.zip') === TRUE) {
    
     for ($i = 0; $i < $zip->numFiles; $i++) {
         if( pathinfo($zip->getNameIndex($i)['extension'] != "php")){
            $zip->extractTo('/my/destination/dir/', $zip->getNameIndex($i));
         }
    }
       $zip->close();
    }
    

    Or this for PHP < 5.5:

    $zip = new ZipArchive;
    if ($zip->open('test.zip') === TRUE) {
    
     for ($i = 0; $i < $zip->numFiles; $i++) {
         $path_info = pathinfo($zip->getNameIndex($i));
         $ext = $path_info['extension'];
         if( $ext != "php")){
            $zip->extractTo('/my/destination/dir/', $zip->getNameIndex($i));
         }
    }
       $zip->close();
    }
    

    The only difference between the two is the pathinfo function. Both will loop all files inside the zip file and, if the file extension isn't php, extracts it to /my/destination/dir/.