PHP.mk документација

ZipArchive::extractTo

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

ziparchive.extractto.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека ziparchive.extractto.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
ZipArchive::extractTo

Референца за `ziparchive.extractto.php` со подобрена типографија и навигација.

ziparchive.extractto.php

ZipArchive::extractTo

(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)

ZipArchive::extractToИзвлечи ја содржината на архивата

= NULL

public ZipArchive::extractTo(string $pathto, array|string|null $files = null): bool

Извлечете ја целосната архива или дадените датотеки на наведената дестинација.

Ги ескејпува специјалните знаци во стринг за употреба во SQL изјава

Стандардните дозволи за извлечените датотеки и директориуми даваат најширок можен пристап. Ова може да се ограничи со поставување на тековната маска за права (umask), која може да се промени со користење на umask().

Од безбедносни причини, оригиналните дозволи не се враќаат. За пример како да ги вратите, видете го примерок од код Пред PHP 7.2.0, користењето на ZipArchive::getExternalAttributesIndex() page.

Параметри

pathto

Локација каде да се извлечат датотеките.

files

Записите за извлекување. Прифаќа или едно име на запис или низа од имиња.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Примери

Пример #1 Извлечи ги сите записи

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

Пример #2 Извлечи два записи

<?php
$zip
= new ZipArchive;
$res = $zip->open('test_im.zip');
if (
$res === TRUE) {
$zip->extractTo('/my/destination/dir/', array('pear_item.gif', 'testfromfile.php'));
$zip->close();
echo
'ok';
} else {
echo
'failed';
}
?>

Белешки

Забелешка:

Windows NTFS датотечните системи не поддржуваат некои знаци во имињата на датотеките, имено <|>*?":. Имињата на датотеките со точка на крајот исто така не се поддржани. Спротивно на некои алатки за извлекување, овој метод не ги заменува овие знаци со подвлекување, туку наместо тоа не успева да ги извлече таквите датотеки.

Белешки од корисници — Интерпретира стринг од XML во објект

php-dev на proneticas dot net
пред 15 години
If you want to copy one file at a time and remove the folder name that is stored in the ZIP file, so you don't have to create directories from the ZIP itself, then use this snippet (basically collapses the ZIP file into one Folder).

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {
    for($i = 0; $i < $zip->numFiles; $i++) {
        $filename = $zip->getNameIndex($i);
        $fileinfo = pathinfo($filename);
        copy("zip://".$path."#".$filename, "/your/new/destination/".$fileinfo['basename']);
    }                   
    $zip->close();                   
}

?>

* On a side note, you can also use $_FILES['userfile']['tmp_name'] as the $path for an uploaded ZIP so you never have to move it or extract a uploaded zip file.

Cheers!

ProNeticas Dev Team
Анонимен
пред 8 години
If you want to extract the files just to the current folder, simply use
$zip->extractTo(".");

It took me hours to figure this out.
randolphothegreat at yahoo dot com
пред 11 години
The extractTo() method does not offer any parameter to allow extracting files and folders recursively from another (parent) folder inside the ZIP archive. With the following method it is possible:

<?php
  class my_ZipArchive extends ZipArchive
  {
    public function extractSubdirTo($destination, $subdir)
    {
      $errors = array();

      // Prepare dirs
      $destination = str_replace(array("/", "\\"), DIRECTORY_SEPARATOR, $destination);
      $subdir = str_replace(array("/", "\\"), "/", $subdir);

      if (substr($destination, mb_strlen(DIRECTORY_SEPARATOR, "UTF-8") * -1) != DIRECTORY_SEPARATOR)
        $destination .= DIRECTORY_SEPARATOR;

      if (substr($subdir, -1) != "/")
        $subdir .= "/";

      // Extract files
      for ($i = 0; $i < $this->numFiles; $i++)
      {
        $filename = $this->getNameIndex($i);

        if (substr($filename, 0, mb_strlen($subdir, "UTF-8")) == $subdir)
        {
          $relativePath = substr($filename, mb_strlen($subdir, "UTF-8"));
          $relativePath = str_replace(array("/", "\\"), DIRECTORY_SEPARATOR, $relativePath);

          if (mb_strlen($relativePath, "UTF-8") > 0)
          {
            if (substr($filename, -1) == "/")  // Directory
            {
              // New dir
              if (!is_dir($destination . $relativePath))
                if (!@mkdir($destination . $relativePath, 0755, true))
                  $errors[$i] = $filename;
            }
            else
            {
              if (dirname($relativePath) != ".")
              {
                if (!is_dir($destination . dirname($relativePath)))
                {
                  // New dir (for file)
                  @mkdir($destination . dirname($relativePath), 0755, true);
                }
              }

              // New file
              if (@file_put_contents($destination . $relativePath, $this->getFromIndex($i)) === false)
                $errors[$i] = $filename;
            }
          }
        }
      }

      return $errors;
    }
  }
?>

Example:
<?php
  echo "<pre>";

  $zip = new my_ZipArchive();
  if ($zip->open("test.zip") === TRUE)
  {
    $errors = $zip->extractSubdirTo("C:/output", "folder/subfolder/");
    $zip->close();

    echo 'ok, errors: ' . count($errors);
  }
  else
  {
    echo 'failed';
  }
?>
quake2005 на gmail dot com
пред 15 години
If you want to extract one file at a time, you can use this:

<?php

$path = 'zipfile.zip'

$zip = new ZipArchive;
if ($zip->open($path) === true) {
                    
    for($i = 0; $i < $zip->numFiles; $i++) {
                         
        $zip->extractTo('path/to/extraction/', array($zip->getNameIndex($i)));
                        
        // here you can run a custom function for the particular extracted file
                        
    }
                    
    $zip->close();
                    
}

?>
kawzaki на yahoo dot com
пред 16 години
Please be aware of the fact that using this function has OVERWRITE true.

an old file will be overwritten if the achieve (zipped file) contains file matching the same old file name.

old files that has no match in the zip, will be kept as is.

hopefully the someone will explain how to avoid overwriting old files.
cory dot mawhorter на ephective dot com
пред 15 години
This function will flatten a zip file using the ZipArchive class.  

It will extract all the files in the zip and store them in a single destination directory.  That is, no sub-directories will be created.

If anyone knows a better way to determine if an entry is a directory, please chime in.  I feel dirty checking for a trailing slash.

<?php
// dest shouldn't have a trailing slash
function zip_flatten ( $zipfile, $dest='.' )
{
    $zip = new ZipArchive;
    if ( $zip->open( $zipfile ) ) 
    {
        for ( $i=0; $i < $zip->numFiles; $i++ ) 
        {
            $entry = $zip->getNameIndex($i);
            if ( substr( $entry, -1 ) == '/' ) continue; // skip directories
            
            $fp = $zip->getStream( $entry );
            $ofp = fopen( $dest.'/'.basename($entry), 'w' );
            
            if ( ! $fp ) 
                throw new Exception('Unable to extract the file.');
            
            while ( ! feof( $fp ) ) 
                fwrite( $ofp, fread($fp, 8192) );
            
            fclose($fp);
            fclose($ofp);
        }

                $zip->close();
    }
    else
        return false;
    
    return $zip;
}

/*
Example Usage:

zip_flatten( 'test.zip', 'my/path' );
*/
?>

[EDIT BY danbrown AT php DOT net: Added $zip-close() per indication by original poster in follow-up note on 18-APR-2010.]
cucurella на gmail dot com
пред 5 години
// Handling ERROR file by file !!

<?php

$ERROR_UNZIP = false;
$dest = "../";
$zipfile = "test.zip";

$zip = new ZipArchive;

if ($zip->open("$zipfile") === true) {
    
    for ($i = 0; $i < $zip -> numFiles; $i++) {
        $RETVAL = false;

        $filename = $zip->getNameIndex($i);

        $RETVAL = $zip->extractTo($dest,$filename);

        if ($RETVAL) {
            print "$filename ... [ OK ]<br>";
        } else {
            print "$filename ... [ ERROR ]<br>";
            $ERROR_UNZIP = true;
        }
    }

    // close
    $zip -> close();

    // retval
    if ($ERROR_UNZIP) {
        print "<p>ERROR unziping ${zipfile}</p>";
    } else {
        print "<p>Unzip OK</p>";
    }
} else {
    print "<p>ERROR opening ${zipfile}</p>";
}

?>
skrzypecki на gmail dot com
пред 8 години
Please note that the path can not be to long! I am not sure what the maximum length is, didnt find any information about that. But i kept getting issues when using extractTo().

Than after google i found this little comment: https://github.com/composer/composer/issues/2824#issuecomment-308201902

CopyPasted comment:
===
I had this path in my machine:

C:/xampp5.0/htdocs/project-recordando-symfony/project-recordando-symfony
Then I ran composer install or/and composer update and it returned this error:

ErrorException ZipArchive::extractTo...

That error is because your path is too much long, I changed to:

C:/xampp5.0/htdocs/p-symfony/*
and worked!
===
ilya at ilya dot top
пред 8 години
<?php 
    
    // This version allows to see which file will be decompressed and to keep 
    // a follow-up on decompression

    define( 'FILEPATH',     dirname(__FILE__)     . '\\' );
    define( 'TEST',         FILEPATH             . 'test\\' );

$za = new ZipArchive();

$za->open(FILEPATH . 'test.zip');
print_r($za);
var_dump($za);
echo "Nombre de fichiers : " . $za->numFiles . "\n";
echo "Statut : " . $za->status  . "\n";
echo "Statut du système : " . $za->statusSys . "\n";
echo "Nom du fichier : " . $za->filename . "\n";
echo "Commentaire : " . $za->comment . "\n";

/*  in $za->statIndex($i)

    [name] => data/x.luac
    [index] => 451
    [crc] => -1266183263
    [size] => 2936
    [mtime] => 1464790482
    [comp_size] => 976
    [comp_method] => 8
*/

for ($i=0; $i<$za->numFiles;$i++) {
    echo "index : $i\n";
    $name = $za->statIndex($i)['name'];
    $size = $za->statIndex($i)['size'];
    $comp_size = $za->statIndex($i)['comp_size'];
    print_r($name . ' [ ' . $size . '>' . $comp_size . ']' );
    $za->extractTo(TEST,$name);
}
echo "Nombre de fichiers :" . $za->numFiles . "\n";    

?>
sachinyadav на live dot com
пред 15 години
This script will search for ".txt" file(any file name) inside test.zip archive. Suppose, 'example.txt' file is found then the script will copy 'example.txt' to "txt_files" directory and rename it to 'test.zip.txt' and will remove all the blank lines from 'test.zip.txt' and resave and will exit the loop without searching remaining entries. 
This script can be useful to extract .DIZ and GIF files to display ZIP archive details in your script.
<?php 
   $value="test.zip"; 
   $filename="zip_files/$value"; 
   $zip = new ZipArchive;
     if ($zip->open($filename) === true) {
      echo "Generating TEXT file.";
          for($i = 0; $i < $zip->numFiles; $i++) { 
             $entry = $zip->getNameIndex($i);
               if(preg_match('#\.(txt)$#i', $entry))
                {
                ////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
                copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt'); 
                $content = file_get_contents("txt_files/$value.txt");
                $newcontent = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $content);
                file_put_contents("txt_files/$value.txt", "$newcontent");
                break;
                } 
              }  
             $zip->close();
            }
    else{
         echo "ZIP archive failed";
        }
?>

enjoy PHP programming.
Sachin Yadav
tBone
пред 17 години
This function, at least from my experience, maintains/forces the directory structure within the ZIP file.

ie. if you have FOLDER1/File1.txt in the zip file and you use
$zip->extractTo('/extract', 'FOLDER1/File1.txt');
the location of the extracted file will be:
/extract/FOLDER1/File1.txt
ben dot tyger на tygerclan dot net
пред 10 години
Note, in Linux (possibly other *nix platforms too) there is no way to extract hidden files ( aka filename starting with a '.') from a Zip archive.
icixtec at gmail dot com
пред 6 години
Para casos donde sea necesario descomprimir archivos sin saber si el nombre está en mayúsculas o minúsculas:

$zip = new ZipArchive;
if ($zip->open('myfile.zip') === TRUE) {
    //no funciona
    //$zip->extractTo('./', array( 'file1.XML', 'file1.xml'));
    //funciona
    $zip->extractTo('./', 'file1.XML' );
    $zip->extractTo('./', 'file1.xml' );
    $zip->close();
}
ohcc на 163 dot com
пред 8 години
WARNING!!!!

if you are running php under Apache, a .htaccess file inside the zip file may fail the extractTo() method.
Анонимен
пред 16 години
I found it useful to add this to a function.

<?php
/**
*  Extracts a ZIP archive to the specified extract path
*
*  @param string $file The ZIP archive to extract (including the path)    
*  @param string $extractPath The path to extract the ZIP archive to
*
*  @return boolean TURE if the ZIP archive is successfully extracted, FALSE if there was an errror 
*  
*/
function zip_extract($file, $extractPath) {

    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
        $zip->extractTo($extractPath);
        $zip->close();
        return TRUE;
    } else {
        return FALSE;
    }

} // end function
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.