note 116353 added to ziparchive.extractto
| From: | stanislav dot eckert at vizson dot de | Date: | Wed, 17 Dec 2014 04:03:37 +0000 |
| Subject: | note 116353 added to ziparchive.extractto | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-201211@lists.php.net to get a copy of this message | ||
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';
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 85.179.4.202
----
Manual Page -- http://php.net/manual/en/ziparchive.extractto.php
Edit -- https://master.php.net/note/edit/116353
Del: integrated -- https://master.php.net/note/delete/116353/integrated
Del: useless -- https://master.php.net/note/delete/116353/useless
Del: bad code -- https://master.php.net/note/delete/116353/bad+code
Del: spam -- https://master.php.net/note/delete/116353/spam
Del: non-english -- https://master.php.net/note/delete/116353/non-english
Del: in docs -- https://master.php.net/note/delete/116353/in+docs
Del: other reasons-- https://master.php.net/note/delete/116353
Reject -- https://master.php.net/note/reject/116353
Search -- https://master.php.net/manage/user-notes.php