very short version of function for unzipping files with folders structure:
<?php
function unzip($file){
$zip=zip_open(realpath(".")."/".$file);
if(!$zip) {return("Unable to proccess file '{$file}'");}
$e='';
while($zip_entry=zip_read($zip)) {
$zdir=dirname(zip_entry_name($zip_entry));
$zname=zip_entry_name($zip_entry);
if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'";continue;}
if(!is_dir($zdir)) mkdirr($zdir,0777);
#print "{$zdir} | {$zname} \n";
$zip_fs=zip_entry_filesize($zip_entry);
if(empty($zip_fs)) continue;
$zz=zip_entry_read($zip_entry,$zip_fs);
$z=fopen($zname,"w");
fwrite($z,$zz);
fclose($z);
zip_entry_close($zip_entry);
}
zip_close($zip);
return($e);
}
function mkdirr($pn,$mode=null) {
if(is_dir($pn)||empty($pn)) return true;
$pn=str_replace(array('/', ''),DIRECTORY_SEPARATOR,$pn);
if(is_file($pn)) {trigger_error('mkdirr() File exists', E_USER_WARNING);return false;}
$next_pathname=substr($pn,0,strrpos($pn,DIRECTORY_SEPARATOR));
if(mkdirr($next_pathname,$mode)) {if(!file_exists($pn)) {return mkdir($pn,$mode);} }
return false;
}
unzip("test.zip");
?>
have a nice day :)
Funções para Zip
Índice
- zip_close — Fecha um arquivo ZIP
- zip_entry_close — Fecha o arquivo que está aberto
- zip_entry_compressedsize — Recupera o tamanho compactado do arquivo que está dentro do arquivo ZIP
- zip_entry_compressionmethod — Recupera qual o método de compressão foi utilizado no arquivo
- zip_entry_filesize — Retorna o tamanho de um diretório de entrada
- zip_entry_name — Retorna o nome do arquivo
- zip_entry_open — Abre um arquivo do arquivo ZIP
- zip_entry_read — Lê de um arquivo aberto
- zip_open — Abre um arquivo ZIPado
- zip_read — Lê a próxima entrada em um arquivo ZIPado
Funções para Zip
yarms at mail dot ru
15-Aug-2009 04:24
15-Aug-2009 04:24
lostdreamer_nl at hotmail dot com
08-Oct-2008 08:22
08-Oct-2008 08:22
in regards to the extracting via unzip.lib.php:
Don't forget to also put in the file path.
Otherwise you end up with a lot of files in the wrong folder...
<?php
require_once("zip.lib.php");
require_once("unzip.lib.php");
$zip = new SimpleUnzip();
$filename = "myzippedfile.zip";
$entries = $zip->ReadFile($filename);
foreach ($entries as $entry){
$fh = fopen($entry->Path .'/'.$entry->Name, 'w', false);
fwrite($fh,$entry->Data);
fclose($fh);
}
?>
phillpafford+php at gmail dot com
12-Jun-2008 01:28
12-Jun-2008 01:28
You could just use the linux commands
<?php
// Get the date
$date = date("m-d-y");
// Make Zip name
$zipname = "archive/site-script-backup." . $date . ".zip";
// Make a zip file
$cmd = `zip -r $zipname *`;
?>
fgarciarico at gmail dot com
26-May-2008 06:19
26-May-2008 06:19
Using the same scripts as the last message:
\libraries\zip.lib.php
\libraries\unzip.lib.php
you can also extract all the files included in a zip file. This is my own example:
require_once("zip.lib.php");
require_once("unzip.lib.php");
$zip = new SimpleUnzip();
$filename = "myzippedfile.zip";
$entries = $zip->ReadFile($filename);
foreach ($entries as $entry){
$fh = fopen($entry->Name, 'w', false);
fwrite($fh,$entry->Data);
fclose($fh);
}
cusimar9 at hotmail dot com
13-May-2008 04:06
13-May-2008 04:06
Just to second the comments above and say that the zipfile class in phpMyAdmin is excellent.
There are 2 files when you download phpMyAdmin:
\libraries\zip.lib.php
\libraries\unzip.lib.php
Here is a small example:
<?php
$zip = new zipfile();
$filename = "1.jpg";
$fsize = @filesize($filename);
$fh = fopen($filename, 'rb', false);
$data = fread($fh, $fsize);
$zip->addFile($data,$filename);
$zipcontents = $zip->file();
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"TheZip.zip\"");
header("Content-length: " . strlen($zipcontents) . "\n\n");
// output data
echo $zipcontents;
?>
rodrigo dot moraes at gmail dot com
29-Jan-2008 03:56
29-Jan-2008 03:56
Here's a more simple extended class to add a whole directory recursively, keeping the same structure. It uses SPL.
<?php
class MyZipArchive extends ZipArchive
{
/**
*
* Adds a directory recursively.
*
* @param string $filename The path to the file to add.
*
* @param string $localname Local name inside ZIP archive.
*
*/
public function addDir($filename, $localname)
{
$this->addEmptyDir($localname);
$iter = new RecursiveDirectoryIterator($filename);
foreach ($iter as $fileinfo) {
if (! $fileinfo->isFile() && !$fileinfo->isDir()) {
continue;
}
$method = $fileinfo->isFile() ? 'addFile' : 'addDir';
$this->$method($fileinfo->getPathname(), $localname . '/' .
$fileinfo->getFilename());
}
}
}
?>
mmj48 at gmail dot com
08-Nov-2007 01:39
08-Nov-2007 01:39
Heres a function I wrote that will extract a zip file with the same directory structure...
Enjoy:
<?php
function unzip($zipfile)
{
$zip = zip_open($zipfile);
while ($zip_entry = zip_read($zip)) {
zip_entry_open($zip, $zip_entry);
if (substr(zip_entry_name($zip_entry), -1) == '/') {
$zdir = substr(zip_entry_name($zip_entry), 0, -1);
if (file_exists($zdir)) {
trigger_error('Directory "<b>' . $zdir . '</b>" exists', E_USER_ERROR);
return false;
}
mkdir($zdir);
}
else {
$name = zip_entry_name($zip_entry);
if (file_exists($name)) {
trigger_error('File "<b>' . $name . '</b>" exists', E_USER_ERROR);
return false;
}
$fopen = fopen($name, "w");
fwrite($fopen, zip_entry_read($zip_entry, zip_entry_filesize($zip_entry)), zip_entry_filesize($zip_entry));
}
zip_entry_close($zip_entry);
}
zip_close($zip);
return true;
}
?>
nheimann at gmx dot net
03-Nov-2007 03:19
03-Nov-2007 03:19
With this extension you can Add dirs with files with the ZipArchive Object
<?php
/**
* FlxZipArchive, Extends ZipArchiv.
* Add Dirs with Files and Subdirs.
*
* <code>
* $archive = new FlxZipArchive;
* // .....
* $archive->addDir( 'test/blub', 'blub' );
* </code>
*/
class FlxZipArchive extends ZipArchive {
/**
* Add a Dir with Files and Subdirs to the archive
*
* @param string $location Real Location
* @param string $name Name in Archive
* @author Nicolas Heimann
* @access private
**/
public function addDir($location, $name) {
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
// } // EO addDir;
/**
* Add Files & Dirs to archive.
*
* @param string $location Real Location
* @param string $name Name in Archive
* @author Nicolas Heimann
* @access private
**/
private function addDirDo($location, $name) {
$name .= '/';
$location .= '/';
// Read all Files in Dir
$dir = opendir ($location);
while ($file = readdir($dir))
{
if ($file == '.' || $file == '..') continue;
// Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
$do = (filetype() == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
} // EO addDirDo();
}
?>
bushj at rpi dot edu
25-Jun-2007 05:59
25-Jun-2007 05:59
I made a zip stream handler in case your distribution does not have the built in one using the new ZipArchive system. This one also features the ability to grab entries by index as well as by name. It is similar in capabilities to the builtin gzip/bzip2 compression stream handlers (http://us2.php.net/manual/en/wrappers.compression.php) except it does not support writing.
To use:
fopen('zip://absolute/path/to/file.zip?entryname', $mode) or
fopen('zip://absolute/path/to/file.zip#entryindex', $mode) or
fopen('zip://absolute/path/to/file.zip', $mode)
$mode can only be 'r' or 'rb'. In the last case the first entry in the zip file is used.
<?php
class ZipStream {
public $zip; //the zip file
public $entry; //the opened zip entry
public $length; //the uncompressed size of the zip entry
public $position; //the current position in the zip entry read
//Opens the zip file then retrieves and opens the entry to stream
public function stream_open($path, $mode, $options, &$opened_path) {
if ($mode != 'r' && $mode != 'rb') //only accept r and rb modes, no writing!
return false;
$path = 'file:///'.substr($path, 6); //switch out file:/// for zip:// so we can use url_parse
$url = parse_url($path);
//open the zip file
$filename = $url['path'];
$this->zip = zip_open($filename);
if (!is_resource($this->zip))
return false;
//if entry name is given, find that entry
if (array_key_exists('query', $url) && $url['query']) {
$path = $url['query'];
do {
$this->entry = zip_read($this->zip);
if (!is_resource($this->entry))
return false;
} while (zip_entry_name($this->entry) != $path);
} else { //otherwise get it by index (default to 0)
$id = 0;
if (array_key_exists('fragment', $url) && is_int($url['fragment']))
$id = $url['fragment']*1;
for ($i = 0; $i <= $id; $i++) {
$this->entry = zip_read($this->zip);
if (!is_resource($this->entry))
return false;
}
}
//setup length and open the entry for reading
$this->length = zip_entry_filesize($this->entry);
$this->position = 0;
zip_entry_open($this->zip, $this->entry, $mode);
return true;
}
//Closes the zip entry and file
public function stream_close() { @zip_entry_close($this->entry); @zip_close($this->zip); }
//Returns how many bytes have been read from the zip entry
public function stream_tell() { return $this->position; }
//Returns true if the end of the zip entry has been reached
public function stream_eof() { return $this->position >= $this->length; }
//Returns the stat array, only 'size' is filled in with the uncompressed zip entry size
public function url_stat() { return array('dev'=>0, 'ino'=>0, 'mode'=>0, 'nlink'=>0, 'uid'=>0, 'gid'=>0, 'rdev'=>0, 'size'=>$this->length, 'atime'=>0, 'mtime'=>0, 'ctime'=>0, 'blksize'=>0, 'blocks'=>0); }
//Reads the next $count bytes or until the end of the zip entry. Returns the data or false if no data was read.
public function stream_read($count) {
$this->position += $count;
if ($this->position > $this->length)
$this->position = $this->length;
return zip_entry_read($this->entry, $count);
}
}
//Register the zip stream handler
stream_wrapper_register('zip', 'ZipStream'); //if this fails there is already a zip stream handler and we will just use that one
?>
darkstream777 at gmx dot net
15-May-2007 11:19
15-May-2007 11:19
Hi,
i modified the function from nielsvandenberge, now you
can also use relative path's, i added also error messages
and another small highlights, have fun.
<?php
/**
* Unzip the source_file in the destination dir
*
* @param string The path to the ZIP-file.
* @param string The path where the zipfile should be unpacked, if false the directory of the zip-file is used
* @param boolean Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
* @param boolean Overwrite existing files (true) or not (false)
*
* @return boolean Succesful or not
*/
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
if(function_exists("zip_open"))
{
if(!is_resource(zip_open($src_file)))
{
$src_file=dirname($_SERVER['SCRIPT_FILENAME'])."/".$src_file;
}
if (is_resource($zip = zip_open($src_file)))
{
$splitter = ($create_zip_name_dir === true) ? "." : "/";
if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
// Create the directories to the destination dir if they don't already exist
create_dirs($dest_dir);
// For every file in the zip-packet
while ($zip_entry = zip_read($zip))
{
// Now we're going to create the directories in the destination directories
// If the file is not in the root dir
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
if ($pos_last_slash !== false)
{
// Create the directory where the zip-entry should be saved (with a "/" at the end)
create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
}
// Open the entry
if (zip_entry_open($zip,$zip_entry,"r"))
{
// The name of the file to save on the disk
$file_name = $dest_dir.zip_entry_name($zip_entry);
// Check if the files should be overwritten or not
if ($overwrite === true || $overwrite === false && !is_file($file_name))
{
// Get the content of the zip entry
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
if(!is_dir($file_name))
file_put_contents($file_name, $fstream );
// Set the rights
if(file_exists($file_name))
{
chmod($file_name, 0777);
echo "<span style=\"color:#1da319;\">file saved: </span>".$file_name."<br />";
}
else
{
echo "<span style=\"color:red;\">file not found: </span>".$file_name."<br />";
}
}
// Close the entry
zip_entry_close($zip_entry);
}
}
// Close the zip-file
zip_close($zip);
}
else
{
echo "No Zip Archive Found.";
return false;
}
return true;
}
else
{
if(version_compare(phpversion(), "5.2.0", "<"))
$infoVersion="(use PHP 5.2.0 or later)";
echo "You need to install/enable the php_zip.dll extension $infoVersion";
}
}
function create_dirs($path)
{
if (!is_dir($path))
{
$directory_path = "";
$directories = explode("/",$path);
array_pop($directories);
foreach($directories as $directory)
{
$directory_path .= $directory."/";
if (!is_dir($directory_path))
{
mkdir($directory_path);
chmod($directory_path, 0777);
}
}
}
}
?>
greetings darki777
nielsvandenberge at hotmail dot com
11-May-2007 09:29
11-May-2007 09:29
This is the function I use to unzip a file.
It includes the following options:
* Unzip in any directory you like
* Unzip in the directory of the zip file
* Unzip in a directory with the zipfile's name in the directory of the zip file. (i.e.: C:\test.zip will be unzipped in C:\test\)
* Overwrite existing files or not
* It creates non existing directories with the function Create_dirs($path)
You should use absolute paths with slashes (/) instead of backslashes (\).
I tested it with PHP 5.2.0 with php_zip.dll extension loaded
<?php
/**
* Unzip the source_file in the destination dir
*
* @param string The path to the ZIP-file.
* @param string The path where the zipfile should be unpacked, if false the directory of the zip-file is used
* @param boolean Indicates if the files will be unpacked in a directory with the name of the zip-file (true) or not (false) (only if the destination directory is set to false!)
* @param boolean Overwrite existing files (true) or not (false)
*
* @return boolean Succesful or not
*/
function unzip($src_file, $dest_dir=false, $create_zip_name_dir=true, $overwrite=true)
{
if ($zip = zip_open($src_file))
{
if ($zip)
{
$splitter = ($create_zip_name_dir === true) ? "." : "/";
if ($dest_dir === false) $dest_dir = substr($src_file, 0, strrpos($src_file, $splitter))."/";
// Create the directories to the destination dir if they don't already exist
create_dirs($dest_dir);
// For every file in the zip-packet
while ($zip_entry = zip_read($zip))
{
// Now we're going to create the directories in the destination directories
// If the file is not in the root dir
$pos_last_slash = strrpos(zip_entry_name($zip_entry), "/");
if ($pos_last_slash !== false)
{
// Create the directory where the zip-entry should be saved (with a "/" at the end)
create_dirs($dest_dir.substr(zip_entry_name($zip_entry), 0, $pos_last_slash+1));
}
// Open the entry
if (zip_entry_open($zip,$zip_entry,"r"))
{
// The name of the file to save on the disk
$file_name = $dest_dir.zip_entry_name($zip_entry);
// Check if the files should be overwritten or not
if ($overwrite === true || $overwrite === false && !is_file($file_name))
{
// Get the content of the zip entry
$fstream = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
file_put_contents($file_name, $fstream );
// Set the rights
chmod($file_name, 0777);
echo "save: ".$file_name."<br />";
}
// Close the entry
zip_entry_close($zip_entry);
}
}
// Close the zip-file
zip_close($zip);
}
}
else
{
return false;
}
return true;
}
/**
* This function creates recursive directories if it doesn't already exist
*
* @param String The path that should be created
*
* @return void
*/
function create_dirs($path)
{
if (!is_dir($path))
{
$directory_path = "";
$directories = explode("/",$path);
array_pop($directories);
foreach($directories as $directory)
{
$directory_path .= $directory."/";
if (!is_dir($directory_path))
{
mkdir($directory_path);
chmod($directory_path, 0777);
}
}
}
}
// Extract C:/zipfiletest/zip-file.zip to C:/zipfiletest/zip-file/ and overwrites existing files
unzip("C:/zipfiletest/zip-file.zip", false, true, true);
// Extract C:/zipfiletest/zip-file.zip to C:/another_map/zipfiletest/ and doesn't overwrite existing files. NOTE: It doesn't create a map with the zip-file-name!
unzip("C:/zipfiletest/zip-file.zip", "C:/another_map/zipfiletest/", true, false);
?>
jeswanth@gmail
30-Apr-2007 07:55
30-Apr-2007 07:55
Hi, all
There are lot of functions given below which etracts files, but what they lack is setting file permissions. On some servers file permissions are very important and the script cease to work after creating first directory, So I have added chmod to the code. There is only one limitation to the code, files without file extension are neither treated as files or directories so they are not chmoded, anyway this does not affect the code. Hope this helps.
<?php
function unpackZip($dir,$file) {
if ($zip = zip_open($dir.$file.".zip")) {
if ($zip) {
mkdir($dir.$file);
chmod($dir.$file, 0777);
while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip,$zip_entry,"r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
$dir_name = dirname(zip_entry_name($zip_entry));
if ($dir_name != ".") {
$dir_op = $dir.$file."/";
foreach ( explode("/",$dir_name) as $k) {
$dir_op = $dir_op . $k;
if (is_file($dir_op)) unlink($dir_op);
if (!is_dir($dir_op)) mkdir($dir_op);
chmod($dir_op, 0777);
$dir_op = $dir_op . "/" ;
}
}
$fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w+");
chmod($dir.$file."/".zip_entry_name($zip_entry), 0777);
fwrite($fp,$buf);
fclose($fp);
zip_entry_close($zip_entry);
} else
return false;
}
zip_close($zip);
}
} else
return false;
return true;
}
$dir = $_SERVER['DOCUMENT_ROOT']."/"."destdirectory/";
$file = 'zipfilename_without_extension';
unpackZip($dir,$file);
$print = $_SERVER['DOCUMENT_ROOT'];
?>
bholub at chiefprojects dot com
17-Oct-2006 07:14
17-Oct-2006 07:14
This will simply unpack (including directories) $zip to $dir -- in this example the zip is being uploaded.
<?php
$dir = 'C:\\reports-temp\\';
$zip = zip_open($_FILES['report_zip']['tmp_name']);
while($zip_entry = zip_read($zip)) {
$entry = zip_entry_open($zip,$zip_entry);
$filename = zip_entry_name($zip_entry);
$target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
$filesize = zip_entry_filesize($zip_entry);
if (is_dir($target_dir) || mkdir($target_dir)) {
if ($filesize > 0) {
$contents = zip_entry_read($zip_entry, $filesize);
file_put_contents($dir.$filename,$contents);
}
}
}
?>
Mishania at ketsujin dot com
06-Oct-2006 03:39
06-Oct-2006 03:39
Notes from phpContrib [ a t ] eSurfers D o t COM are a ROCK!!!
1) In order to make it work U'll probably need:
** Allow Apache service to interact with desktop, but in that case U will notice momentarely console window opens and closes. That's may be annoying. The elegant solution instead of allowing interaction is redirect the command to some temporary file, and get rid of it later on:
define('UNZIP_CMD','unzip -o @_SRC_@ -x -d
@_DST_@ > tmpfile.txt');
2) I would recommend to use 7-zip, it's free and completely relyable. Also, it's comes with stand alone console executable which makes it quite convenient to place it in some exec library folder within your source, and refferering directly to it.
define("UNZIP_CMD","7za.exe x @_SRC_@ -o@_DST_@ > tmpfile.txt");
10-May-2006 02:23
I try to use the function unpackZip from schore at NOSPAM dot hotmail dot com.
it appears that the fclose instruction is missing. Without that instruction, i've got some trouble to unpack zip file with recursive folders.
Here is the new code with the missing instruction
<?php
function unpackZip($dir,$file) {
if ($zip = zip_open($dir.$file.".zip")) {
if ($zip) {
mkdir($dir.$file);
while ($zip_entry = zip_read($zip)) {
if (zip_entry_open($zip,$zip_entry,"r")) {
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
$dir_name = dirname(zip_entry_name($zip_entry));
if ($dir_name != ".") {
$dir_op = $dir.$file."/";
foreach ( explode("/",$dir_name) as $k) {
$dir_op = $dir_op . $k;
if (is_file($dir_op)) unlink($dir_op);
if (!is_dir($dir_op)) mkdir($dir_op);
$dir_op = $dir_op . "/" ;
}
}
$fp=fopen($dir.$file."/".zip_entry_name($zip_entry),"w");
fwrite($fp,$buf);
fclose($fp);
zip_entry_close($zip_entry);
} else
return false;
}
zip_close($zip);
}
} else
return false;
return true;
}
?>
angelnsn1 at hotmail dot com
27-Jan-2006 02:06
27-Jan-2006 02:06
this function extract all files and subdirectories, you can choose verbose mode for get paths of files extracted. the function return a msg what indicate the error, if msg is OK, all is done.
---
code:
<?php
function unzip($dir, $file, $verbose = 0) {
$dir_path = "$dir$file";
$zip_path = "$dir$file.zip";
$ERROR_MSGS[0] = "OK";
$ERROR_MSGS[1] = "Zip path $zip_path doesn't exists.";
$ERROR_MSGS[2] = "Directory $dir_path for unzip the pack already exists, impossible continue.";
$ERROR_MSGS[3] = "Error while opening the $zip_path file.";
$ERROR = 0;
if (file_exists($zip_path)) {
if (!file_exists($dir_path)) {
mkdir($dir_path);
if (($link = zip_open($zip_path))) {
while (($zip_entry = zip_read($link)) && (!$ERROR)) {
if (zip_entry_open($link, $zip_entry, "r")) {
$data = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
$dir_name = dirname(zip_entry_name($zip_entry));
$name = zip_entry_name($zip_entry);
if ($name[strlen($name)-1] == '/') {
$base = "$dir_path/";
foreach ( explode("/", $name) as $k) {
$base .= "$k/";
if (!file_exists($base))
mkdir($base);
}
}
else {
$name = "$dir_path/$name";
if ($verbose)
echo "extracting: $name<br>";
$stream = fopen($name, "w");
fwrite($stream, $data);
}
zip_entry_close($zip_entry);
}
else
$ERROR = 4;
}
zip_close($link);
}
else
$ERROR = "3";
}
else
$ERROR = 2;
}
else
$ERROR = 1;
return $ERROR_MSGS[$ERROR];
}
?>
---
example:
<?php
$error = unzip("d:/www/dir/", "zipname", 1);
echo $error;
?>
---
i hope this help you,
good bye.
ringu at mail dot ru
20-Aug-2005 01:12
20-Aug-2005 01:12
i try to find function that will show exists file in zip archive or not. of course i not found it. and so write mine:
first will just check archive for list of files, if not found all files function return FALSE:
<?php
function zipx_entries_exists()
{
$names=array();
$args=func_get_args();
$far_size=count($args);
if($args[0])
{
for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
for($x=1; $x<=$far_size; $t+=in_array($args[$x], $names), $x++);
return $t==--$far_size;
}else{
return 'No zip file in descriptor!';
}
}
example:
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_exists($zip, 'photo_1.jpg', 'photo_2.jpg'));
second function will try to find files in zip, if not found it return string with names of not found files with specified delimeter:
function zipx_entries_nonexists_list()
{
$names=array();
$args=func_get_args();
$m=NULL;
$far_size=count($args);
if($args[0])
{
for(; $zip_entry=zip_read($args[0]); $names[]= zip_entry_name($zip_entry));
for($x=2; $x<=$far_size; $m.=(in_array($args[$x], $names) ? NULL : $args[$x].$args[1]), $x++);
return trim($m, $args[1]);
}else{
return 'No zip file in descriptor!';
}
}
?>
example:
<?php
$zip=zip_open('any_zip_file_zip');
var_dump(zip_entries_nonexists_list($zip, '<br />', 'photo_1.jpg', 'photo_2.jpg'));
?>
it will return if not found files:
photo_1.jpg<br />photo_2.jpg
tom
28-Jun-2005 04:33
28-Jun-2005 04:33
If you just want to unzip a zip folder an alternative to some of the lengthy functions below is:
<?php
function unzip($zip_file, $src_dir, $extract_dir)
{
copy($src_dir . "/" . $zip_file, $extract_dir . "/" . $zip_file);
chdir($extract_dir);
shell_exec("unzip $zip_file");
}
?>
You don't need the ZIP extension for this.
candido1212 at yahoo dot com dot br
27-Apr-2005 03:52
27-Apr-2005 03:52
New Unzip function, recursive extract
Require mkdirr() (recursive create dir)
<?php
$file = "2537c61ef7f47fc3ae919da08bcc1911.zip";
$dir = getcwd();
function Unzip($dir, $file, $destiny="")
{
$dir .= DIRECTORY_SEPARATOR;
$path_file = $dir . $file;
$zip = zip_open($path_file);
$_tmp = array();
$count=0;
if ($zip)
{
while ($zip_entry = zip_read($zip))
{
$_tmp[$count]["filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["stored_filename"] = zip_entry_name($zip_entry);
$_tmp[$count]["size"] = zip_entry_filesize($zip_entry);
$_tmp[$count]["compressed_size"] = zip_entry_compressedsize($zip_entry);
$_tmp[$count]["mtime"] = "";
$_tmp[$count]["comment"] = "";
$_tmp[$count]["folder"] = dirname(zip_entry_name($zip_entry));
$_tmp[$count]["index"] = $count;
$_tmp[$count]["status"] = "ok";
$_tmp[$count]["method"] = zip_entry_compressionmethod($zip_entry);
if (zip_entry_open($zip, $zip_entry, "r"))
{
$buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
if($destiny)
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $destiny . zip_entry_name($zip_entry));
}
else
{
$path_file = str_replace("/",DIRECTORY_SEPARATOR, $dir . zip_entry_name($zip_entry));
}
$new_dir = dirname($path_file);
// Create Recursive Directory
mkdirr($new_dir);
$fp = fopen($dir . zip_entry_name($zip_entry), "w");
fwrite($fp, $buf);
fclose($fp);
zip_entry_close($zip_entry);
}
echo "\n</pre>";
$count++;
}
zip_close($zip);
}
}
Unzip($dir,$file);
?>
23-Feb-2005 04:54
If (as me) all you wanted to do is store a big string (for example, a serialized array or the like) in a mysql BLOB field, remember that mysql has a COMPRESS() and UNCOMPRESS() pair of functions that do exactly that. Compression/decompression is therefore available also when accessing the DB from other languages like java, etc.
php at isaacschlueter dot com
23-Jun-2004 11:15
23-Jun-2004 11:15
If you don't have the --with-zip=DIR compile option and can't change it, but you do have --with-pear, then you can use the pear Archive_Zip class available at http://cvs.php.net/pear/Archive_Zip/
As of 2004-06-23, the class isn't packaged and auto-documented yet, but like all pear classes, the comments are extremely verbose and helpful, and you can download the php file as a standalone. Just include the Zip.php in your project, and you can use the class.
krishnendu at spymac dot com
31-May-2004 08:28
31-May-2004 08:28
If you want to unzip an password protected file with php..try the following command....it works in Unix/Apache environment...I haven't tested in any other environment...
system("`which unzip` -P Password $zipfile -d $des",$ret_val)
Where $zipfile is the path to the .zip to be unzipped and $des is path to the destination directory.....here both absolute and relative path to the script (which contains this system command) will work...
if everything runs well...file should be unzipped at the $des directory..and you will get 0 value for $ret_val , which means success(info-zip.org)
Regards
Krishnendu
travis
17-Jun-2003 05:06
17-Jun-2003 05:06
just a not of caution--using the dynamic zip class mentioned earlier seems to cause issues with high ascii characters (their values are not preserved correctly, and the file will not unzip)
chris
23-Mar-2003 06:32
23-Mar-2003 06:32
Watch out with archives that contain subfolders if you're using the zip functions to extract archives to actual files. Let's say you're trying to extract foldername/filename.txt from the archive. You can't fopen a directory that doesn't exist, so you'll have to check for the existance of directory foldername and create it if it isn't found, then fopen foldername/filename.txt and begin writing to that.
ottawasixtyseven at hotmail dot com
29-Oct-2002 08:04
29-Oct-2002 08:04
WOW ... after weeks and weeks of research I thought I'd make somebody elses life a little easier. If you're wondering how to make PHP 4.2.3 read windows zip files (winzip, pkzip, etc) do this:
NOTE: THIS IS FOR WINDOWS SERVERS NOT LINUX OR OTHER. You need zziplib for Linux. http://zziplib.sourceforge.net/
ON PHP WINDOWS SERVER
1) Grab the php_zip.dll from the extensions dir in php-4.3.0pre2-Win32.zip
2) Add a line extension=php_zip.dll to your php.ini
3) Restart your web server
php_zip.dll obviously works on PHP 4.3.0pre2 but you can't run Zend Optimizer on PHP 4.3 (yet). You can run Zend Optimizer on PHP 4.2.3 but it doesn't ship with php_zip.dll. The php_zip.dll that ships with PHP 4.3.0pre2 may even work with older version but I haven't tested that.
For documentation on how to use the zip functions (not the gzip functions that are documented on the php site) go here:
http://zziplib.sourceforge.net/zziplib.html
Newbie Von Greenhorn
vangoethem at hotmail dot com
28-Dec-2001 07:51
28-Dec-2001 07:51
If you are looking for a way to create ZIP files dynamically in PHP, you should look at the wonderful zipfile class.
It seems there is no official page for this class. You may get it by retrieving the zip.lib.php from the PhpMyAdmin 2.5.2:
http://www.phpmyadmin.net/
