I am trying to unarchive a zip file that was inside another zip file to get to the xml file that is in the second zip file.
The big challenge with this file is that the files inside the zip file will always be different and therefore unknow. So I created a function to put the list of the archived archives into a text list. Then use this list to unarchive each file and extract the information that is needed from the xml file that is inside the second zip file.
Here is my code so far.
//Set the date
$day = date("mdY");
echo $day."<br>";
//URL to download file from for updating the prescription table
//$url = "ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_".$day.".zip";
$url = "ftp://public.nlm.nih.gov/nlmdata/.dailymed/dm_spl_daily_update_09152016.zip";
//Saving the file on the server.
file_put_contents("Prescription_update.zip", fopen($url, 'r'));
//unzip the downloaded file
$zip = new ZipArchive;
if($zip->open('Prescription_update.zip')){
$path = getcwd() . "/update/";
$path = str_replace("\\","/",$path);
//echo $path;
$zip->extractTo($path);
$zip->close();
print 'ok<br>';
} else {
print 'Failed';
}
// integer starts at 0 before counting
$i = 0;
$dir = '/update/prescription/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory need this for the loop later
echo "There were $i files<br>";
$dh = opendir($dir);
$files = array();
while (false !== ($filename = readdir($dh))) {
$files[] = $filename." \r\n";
}
//Created a list of files in the update/prescription folder
file_put_contents("list.txt", $files);
/*
* Creating a loop here to ready the names and extract the
* XML file from the zipped files that are in the update/prescription folder
*
*/
$ii = 2;
$fileName = new SplFileObject('list.txt');
$fileName->seek($ii);
echo $fileName."<br>"; //return the first file name from list.txt
$zip = new ZipArchive;
$zipObj = getcwd()."/update/prescription/".$fileName;
$zipObj = str_replace("\\","/", $zipObj);
echo $zipObj."<br>";
if($zip->open($zipObj)){
$path = getcwd() . "/update/prescription/tmp/";
$path = str_replace("\\","/",$path);
mkdir($path);
echo $path;
$zip->extractTo($path);
$zip->close();
print 'ok<br>';
} else {
print 'Failed';
}
Can't figure out why the second ZipArchive::extractTo: is throwing the error. I thought it may have been a path problem. I so I did the second string replacement hoping that would clear it up but it did not. So, throwing up my hands and asking for a second set of eyes on this one.
UPDATE ERROR LOG ENTRY
[18-Sep-2016 02:24:24 America/Chicago] PHP 1. {main}() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:0
[18-Sep-2016 02:24:24 America/Chicago] PHP 2. ZipArchive->extractTo() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:76
[18-Sep-2016 02:24:24 America/Chicago] PHP Warning: ZipArchive::close(): Invalid or unitialized Zip object in C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php on line 77
[18-Sep-2016 02:24:24 America/Chicago] PHP Stack trace:
[18-Sep-2016 02:24:24 America/Chicago] PHP 1. {main}() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:0
[18-Sep-2016 02:24:24 America/Chicago] PHP 2. ZipArchive->close() C:\emr-wamp\www\interface\weno\update_prescription_drug_table.php:77
I was going to vote to delete this question but I thought it would be better to leave it over the long run.
The answer is
How to get PHP ZipArchive to work with variable
It seems that the whole name cannot be subbed as a variable. But if you sub part of the name it is allowed.
$zipObj = getcwd()."/update/prescription/".$fileName;
It has to be subbed like
$z->open("update/".$r.".zip"){
//do something here
}
Related
Hello this is my first time posting here, I am not sure how this works but I have included my code below. I would greatly appreciate some help.
I am having trouble with closing my zip file. The markers (print statements) that I have created are being executed. I am only getting an error with $zip->close().
For reference, I have PHP Version 7.4.24 and am I using a Mac. When my colleague ran it on his Windows system, it executed.
This is the error that is displayed in my browser:
Warning: ZipArchive::close(): Failure to create temporary file: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/nameOfMyFolder/folderzip.php on line 55
<?php
// name of directory (folder)
$pathdir = "/Applications/XAMPP/xamppfiles/htdocs/nameOfMyFile/";
//name of zip file to be created when zipped
$zipcreated = "archive.zip";
// new zip class
$zip = new ZipArchive;
if (extension_loaded("zip")){
echo "Zip extension is loaded";
}
//phpinfo();
// PHP Version 7.4.24
// Create a zip file and open it, check if it worked
if($zip -> open($zipcreated, ZipArchive::CREATE ) == TRUE) {
// Store the path into the variable
// opendir opens a directory handle
$dir = opendir($pathdir);
while($file = readdir($dir)) {
// is_file checks if specified file is a regular file
echo $pathdir.$file;
if(is_file($pathdir.$file)) {
$zip -> addFile($pathdir.$file, $file);
echo "File/s copied";
} else {
//echo "File not copied";
}
//echo "While executed";
}
echo "Out of while loop";
$zip->close();
//$zip -> ZipArchive::close();
//zip_close(resource ($zip));
//$zip -> getStatusString();
} else {
die ("Can't open $zipcreated");
}
?>
I've refactored your code and it appears to be working now. Take note of how I used the "! not" condition so the code can exit quicker and it doesn't need to be nested.
<?php
$folder_to_archive = "/path/to/your/folder/";
$zip_file = "archive2.zip";
if (!extension_loaded("zip"))
die("Zip extension could not be loaded" . PHP_EOL);
$zip = new ZipArchive;
if ($zip->open($zip_file, ZipArchive::CREATE) !== true)
die('Could not create Zip File' . PHP_EOL);
$dir = array_diff(scandir($folder_to_archive), ['.','..']);
foreach ($dir as $file) {
$full_filename = $folder_to_archive . $file;
if (!is_file($full_filename))
continue;
$zip->addFile($full_filename, $file);
}
$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 pulling my hair out over here. I have spent the last week trying to figure out why the ZipArchive extractTo method behaves differently on linux than on our test server (WAMP).
Below is the most basic example of the problem. I simply need to extract a zip that has the following structure:
my-zip-file.zip
-username01
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
-username02
--filename01.txt
-images.zip
--image01.png
-songs.zip
--song01.wav
The following code will extract the root zip file and keep the structure on my WAMP server. I do not need to worry about extracting the subfolders yet.
<?php
if(isset($_FILES["zip_file"]["name"])) {
$filename = $_FILES["zip_file"]["name"];
$source = $_FILES["zip_file"]["tmp_name"];
$errors = array();
$name = explode(".", $filename);
$continue = strtolower($name[1]) == 'zip' ? true : false;
if(!$continue) {
$errors[] = "The file you are trying to upload is not a .zip file. Please try again.";
}
$zip = new ZipArchive();
if($zip->open($source) === FALSE)
{
$errors[]= "Failed to open zip file.";
}
if(empty($errors))
{
$zip->extractTo("./uploads");
$zip->close();
$errors[] = "Zip file successfully extracted! <br />";
}
}
?>
The output from the script above on WAMP extracts it correctly (keeping the file structure).
When I run this on our live server the output looks like this:
--username01\filename01.txt
--username01\images.zip
--username01\songs.zip
--username02\filename01.txt
--username02\images.zip
--username02\songs.zip
I cannot figure out why it behaves differently on the live server. Any help will be GREATLY appreciated!
To fix the file paths you can iterate over all extracted files and move them.
Supposing inside your loop over all extracted files you have a variable $source containing the file path (e.g. username01\filename01.txt) you can do the following:
// Get a string with the correct file path
$target = str_replace('\\', '/', $source);
// Create the directory structure to hold the new file
$dir = dirname($target);
if (!is_dir($dir)) {
mkdir($dir, 0777, true);
}
// Move the file to the correct path.
rename($source, $target);
Edit
You should check for a backslash in the file name before executing the logic above. With the iterator, your code should look something like this:
// Assuming the same directory in your code sample.
$dir = new DirectoryIterator('./uploads');
foreach ($dir as $fileinfo) {
if (
$fileinfo->isFile()
&& strpos($fileinfo->getFilename(), '\\') !== false // Checking for a backslash
) {
$source = $fileinfo->getPathname();
// Do the magic, A.K.A. paste the code above
}
}
I am trying to move all the .vtk files and .raw files to a different folder. But it is not being copied. How do I fix this?
<?php
define ('DOC_ROOT', $_SERVER['DOCUMENT_ROOT'].'/');
$src = '/var/www/html/php/';
$dest ='/var/www/html/php/emd/';
$dh = opendir ($src); //Get a directory handle
$validExt = array('vtk','raw'); //Define a list of allowed file types
$filesMoved = 0;
// Loop through all the files in the directory checking them and moving them
while (($file = readdir ($dh)) !== false) {
// Get the file type and convert to lower case so the array search always matches
$fileType = strtolower(pathinfo ($file, PATHINFO_EXTENSION));
if(in_array ($fileType, $validExt)) {
// Move the file - if this is for the web really you should create a web safe file name
if (!$rename($src.$file, $dest.) {
echo "Failed to move {$file} to {$newPath}";
} else {
echo "Moved {$file} to {$newPath}";
$filesMoved++;
}
}
}
echo "{$filesMoved} files were moved";
closedir($dh);
?>
You forgot to add the filename for the destination, change this line:
if (!$rename($src.$file, $dest.) {
into:
if (!$rename($src.$file, $dest.$file) {
If this is not working make sure that the destination directory really exists and that you have write permission to it. If you had enabled error reporting you would have seen an error message like this:
Parse error: parse error in
/path/to/script/rename.php on
line 18
Thanks in advance.
Getting this warning when using below code:
Warning: file_get_contents(test.php) [function.file-get-contents]: failed to open stream: No such file or directory in /path/index.php on line so-n-so.
Here's the code I am using,
<?php
// Scan directory for files
$dir = "path/";
$files = scandir($dir);
// Iterate through the list of files
foreach($files as $file)
{
// Determine info about the file
$parts = pathinfo($file);
// If the file extension == php
if ( $parts['extension'] === "php" )
{
// Read the contents of the file
$contents = file_get_contents($file);
// Find first occurrence of opening template tag
$from = strpos($contents, "{{{{{");
// Find first occurrence of ending template tag
$to = strpos($contents,"}}}}}");
// Pull out the unique name from between the template tags
$uniqueName = substr($contents, $from+5, $to);
// Print out the unique name
echo $uniqueName ."<br/>";
}
}
?>
The error message says that the file isn't found.
This is because scandir() returns only the basename of the files from your directory. It doesn't include the directory name. You could use glob() instead:
$files = glob("$dir/*.php");
This returns the path in the result list, and would also make your extension check redundant.
I would suggest that you need to exclude . and .. from the list of files picked up by scandir() DOCs.
// Iterate through the list of files
foreach($files as $file) {
if('.' == $file or '..' == $file) {
continue;
}
...
Also you need to put the path before your file name:
$contents = file_get_contents($path . $file);