I have a zip file called project.zip with the following structure:
project.zip
\project
\file.pdf
I need to delete file.pdf. I tried the following code but I'm getting an error.
Thanks
$zip = new ZipArchive();
$zip_name = 'path\to\project.zip';
$zip->open( $zip_name );
$zip->deleteName( 'project\file.pdf' );
$zip->close();
I Also tried with a leading backslash but with no success,
$zip->deleteName( 'prject\file.pdf' );
It's weird, but it seems you need to include the base name of the zip file in the filename like this:
$zip->deleteName( 'project/project/file.pdf' );
Try something like this to see what the filename values look like in your zip:
for ($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
echo $filename . "<br>";
}
Also don't forget to close the zip when you are done
$zip->close();
use forward slashes :
$zip->deleteName( 'project/file.pdf' );
Related
I have a folder in my web server were I put zip files that I need to then unzip. I want to do that with php and this is what I have tried but it does not work:
<?php
$file = $_GET["file"];
$zip = new ZipArchive;
$res = $zip->open($file+'.zip');
$zip->extractTo('./');
$zip->close();
?>
The zip files are in the same folder as the php file, but when I go to the php page it does nothing.
By doing some testing I have found out that the script dies on the $zip = new ZipArchive; line
How can I manage this to work?
<?php
$fileName = $_GET['file']; // get file name in the URL param "file"
if (isset($fileName)) { // if $fileName php variable is set than
$zip = new ZipArchive; // create object
$res = $zip->open($fileName); // open archive
if ($res === TRUE) {
$zip->extractTo('./'); // extract contents to destination directory
$zip->close(); //close the archieve
echo 'Extracted file "'.$fileName.'"';
} else {
echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
}
}
else {
echo 'Please set file name in the "file" param';
}
?>
Note:- For More Details Please refer https://www.php.net/manual/en/class.ziparchive.php
I have found the problem.
The code is fine, but the hosting service is not, and they do not have the ZIP extension available right now
Try this code. Also change $zip->open($file+".zip"); to $zip->open($file);.
+ (plus sign) is not concatenation operator in php
<?php
// $_GET["file"] is set to `a.zip`
$file = $_GET["file"];
$zip = new ZipArchive;
$res = $zip->open($file);
$zip->extractTo('./');
$zip->close();
?>
I'm struggling around with a simple PHP functionality: Creating a ZIP Archive with some files in.
The problem is, it does not create only one file called filename.zip but two files called filename.zip.a07600 and filename.zip.b07600. Pls. see the following screenshot:
The two files are perfect in size and I even can rename each of them to filename.zip and extract it without any problems.
Can anybody tell me what is going wrong???
function zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path = array(), $files_array = array()) {
// Archive File Name
$archive_file = $archiveDir."/".$archive_file_name;
// Time-to-live
$archiveTTL = 86400; // 1 day
// Delete old zip file
#unlink($archive_file);
// Create the object
$zip = new ZipArchive();
// Create the file and throw the error if unsuccessful
if ($zip->open($archive_file, ZIPARCHIVE::CREATE) !== TRUE) {
$response->res = "Cannot open '$archive_file'";
return $response;
}
// Add each file of $file_name array to archive
$i = 0;
foreach($files_array as $value){
$expl = explode("/", $value);
$file = $expl[(count($expl)-1)];
$path_file = $file_path[$i] . "/" . $file;
$size = round((filesize ($path_file) / 1024), 0);
if(file_exists($path_file)){
$zip->addFile($path_file, $file);
}
$i++;
}
$zip->close();
// Then send the headers to redirect to the ZIP file
header("HTTP/1.1 303 See Other"); // 303 is technically correct for this type of redirect
header("Location: $archive_file");
exit;
}
The code which calls the function is a file with a switch-case... it is called itself by an ajax-call:
case "zdl":
$files_array = array();
$file_path = array();
foreach ($dbh->query("select GUID, DIRECTORY, BASENAME, ELEMENTID from SMDMS where ELEMENTID = ".$osguid." and PROJECTID = ".$osproject.";") as $subrow) {
$archive_file_name = $subrow['ELEMENTID'].".zip";
$archiveDir = "../".$subrow['DIRECTORY'];
$files_array[] = $archiveDir.DIR_SEPARATOR.$subrow['BASENAME'];
$file_path[] = $archiveDir;
}
zipFilesAndDownload_Defect($archive_file_name, $archiveDir, $file_path, $files_array);
break;
One more code... I tried to rename the latest 123456.zip.a01234 file to 123456.zip and then unlink the old 123456.zip.a01234 (and all prior added .a01234 files) with this function:
function zip_file_exists($pathfile){
$arr = array();
$dir = dirname($pathfile);
$renamed = 0;
foreach(glob($pathfile.'.*') as $file) {
$path_parts = pathinfo($file);
$dirname = $path_parts['dirname'];
$basename = $path_parts['basename'];
$extension = $path_parts['extension'];
$filename = $path_parts['filename'];
if($renamed == 0){
$old_name = $file;
$new_name = str_replace(".".$extension, "", $file);
#copy($old_name, $new_name);
#unlink($old_name);
$renamed = 1;
//file_put_contents($dir."/test.txt", "old_name: ".$old_name." - new_name: ".$new_name." - dirname: ".$dirname." - basename: ".$basename." - extension: ".$extension." - filename: ".$filename." - test: ".$test);
}else{
#unlink($file);
}
}
}
In short: copy works, rename didn't work and "unlink"-doesn't work at all... I'm out of ideas now... :(
ONE MORE TRY: I placed the output of $zip->getStatusString() in a variable and wrote it to a log file... the log entry it produced is: Renaming temporary file failed: No such file or directory.
But as you can see in the graphic above the file 43051221.zip.a07200 is located in the directory where the zip-lib opens it temporarily.
Thank you in advance for your help!
So, after struggling around for days... It was so simple:
Actually I work ONLY on *nix Servers so in my scripts I created the folders dynamically with 0777 Perms. I didn't know that IIS doesn't accept this permissions format at all!
So I remoted to the server, right clicked on the folder Documents (the hierarchically most upper folder of all dynamically added files and folders) and gave full control to all users I found.
Now it works perfect!!! The only thing that would be interesting now is: is this dangerous of any reason???
Thanks for your good will answers...
My suspicion is that your script is hitting the PHP script timeout. PHP zip creates a temporary file to zip in to where the filename is yourfilename.zip.some_random_number. This file is renamed to yourfilename.zip when the zip file is closed. If the script times out it will probably just get left there.
Try reducing the number of files to zip, or increasing the script timeout with set_time_limit()
http://php.net/manual/en/function.set-time-limit.php
I am retrieving my google map in a kmz format like this:
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/temp/map.kmz', file_get_contents('https://mapsengine.google.com/map/kml?mid=zLucZBnh_ipg.kS906psI1W9k') );
$zip = new ZipArchive;
$res = $zip->open($_SERVER['DOCUMENT_ROOT'].'/temp/map.kmz');
if ($res === true)
{
trace("Number of files: $res->numFiles".PHP_EOL);
for( $i = 0; $i < $res->numFiles; $i++ )
{
$stat = $res->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL );
}
}
But no files are showing and $zip->extractTo() is not working either. The file is downloaded on the server and I can extract it manually though. I have tried renaming the file to .zip or .kmz, still not working. I have opened the map.kmz file in Winrar and it does indeed say that it is a zip file format.
Any idea why it's not working? Do I need some special permissions to read the number of files or extract?
Check your file types .mkz and .kmz.
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/temp/map.mkz',
file_get_contents('https://mapsengine.google.com/map/kml? mid=zLucZBnh_ipg.kS906psI1W9k') );
$zip = new ZipArchive;
$res = $zip->open($_SERVER['DOCUMENT_ROOT'].'/temp/map.kmz');
Got tired of the damn class not working, tried this method instead and it works:
$data = file_get_contents("https://mapsengine.google.com/map/kml?mid=zLucZBnh_ipg.kS906psI1W9k");
file_put_contents($_SERVER['DOCUMENT_ROOT'].'/temp/kmz_temp', $data);
ob_start();
passthru("unzip -p {$_SERVER['DOCUMENT_ROOT']}/temp/kmz_temp");
$xml_data = ob_get_clean();
header("Content-type: text/xml");
echo $xml_data;
exit();
Would appreciate some help on this. I've been trying to write a PHP script that Unzips a zip file that has been created using PHP's in-built Zip Archive extension.
The zipping-up process has been very straight forward but now I'm trying to unzip this to a particular folder and it doesn't seem to be working. The only thing it does is create the folder I've asked it to extract to. No files appear in that folder.
I've had no error messages.
Thanks in Advance. Here's my code:
<?php
$root = str_replace('public_html', '', $_SERVER["DOCUMENT_ROOT"]);
$path = $root.'scripts.zip';
$zip = new ZipArchive;
$zipped = $zip->open($path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
$folder = $root.'public_html/scripts/';
if ($zipped) {
$extract = $zip->extractTo($folder);
if ($extract){
echo 'Zip File Extracted';
}
$zip->close();
}
?>
I would modify your code to look like the one below.
What you were doing was creating a new zip file, not extracting the old one. ZIPARCHIVE::CREATE instructs the code to create a zip, ZIPARCHIVE::OVERWRITE tells it to overwrite existing files in the zip.
So you are not extracting anything from the zip. This code below should work
<?php
$root = str_replace('public_html', '', $_SERVER["DOCUMENT_ROOT"]);
$path = $root.'scripts.zip';
$zip = new ZipArchive;
$zipped = $zip->open($path); /*I have removed the ::CREATE & ::OVERWRITE methods*/
$folder = $root.'public_html/scripts/';
if ($zipped) {
$extract = $zip->extractTo($folder);
if ($extract){
echo 'Zip File Extracted';
}
$zip->close();
}
?>
Hope that helps
I would like to extract a zip folder to a location and to replace all files and folders except a few, how can I do this?
I currently do the following.
$backup = realpath('./backup/backup.zip');
$zip = new ZipArchive();
if ($zip->open("$backup", ZIPARCHIVE::OVERWRITE) !== TRUE) {
die ('Could not open archive');
}
$zip->extractTo('minus/');
$zip->close();
How can I put conditions in for what files and folders should NOT be replaced? It would be great if some sort of loop could be used.
Thanks all for any help
You could do something like this, I tested it and it works for me:
// make a list of all the files in the archive
$entries = array();
for ($idx = 0; $idx < $zip->numFiles; $idx++) {
$entries[] = $zip->getNameIndex($idx);
}
// remove $entries for the files you don't want to overwrite
// only extract the remaining $entries
$zip->extractTo('minus/', $entries);
This solution is based on the numFiles property and the getNameIndex method, and it works even when the archive is structured into subfolders (the entries will look like /folder/subfolder/file.ext).
Also, the extractTo method takes a second optional paramer that holds the list of files to be extracted.
If you just want to extract specific files from the archive (and you know what they are) then use the second parameter (entries).
$zip->extractTo('minus/', array('file1.ext', 'newfile2.xml'));
If you want to extract all the files that do not exist, then you can try one of the following:
$files = array();
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
// if $filename not in destination / or whatever the logic is then
$files[] = $filename;
}
$zip->extractTo($path, $files);
$zip->close();
You can also use $zip->getStream( $filename ) to read a stream that you then write to the destination file.