I am using PHP to upload a zip file and extracting it. I was having problems with my validation script, and just discovered that the culprit was Thumbs.db files which windows creates to improve caching. How can I delete these files prior to extracting?
Below is my attempt, but when extracting, other files have also been deleted. I've tried using both deleteIndex() and deleteName(), but get the same results. If I comment out the the line which deletes the Thumbs.db files, I do not experience the unintended deleted files. My syslog() line only indicates that the Thumbs.db files are being deleted.
<?php
$zip = new ZipArchive();
if ($zip->open($_FILES['upload_file']['tmp_name']) === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
//Validate files
$name=$zip->getNameIndex($i);
$pieces=explode(DIRECTORY_SEPARATOR,$name);
if($pieces[count($pieces)-1]=='Thumbs.db'){
//Delete windows created thumb.db files
syslog(LOG_INFO,'delete file '.$name.' with index '.$i);
$zip->deleteIndex($i); //If commented out, I do not experience the wrong files being deleted
//Also deletes wrong files: $zip->deleteName($name);
}
}
$zip->extractTo($myPath);
}
?>
Close the archive after file manipulations and reopen it before extracting:
if ($zip->open($_FILES['upload_file']['tmp_name']) === true) {
for ($i = 0; $i < $zip->numFiles; $i++) {
...
}
$zip->close();
if ($zip->open($_FILES['upload_file']['tmp_name']) === true) {
$zip->extractTo($myPath);
}
}
I believe in your example $zip->extractTo($myPath); return false.
In your particular case it may be simpler to use system utilities to unpack the archive and then delete the files with find.
Related
I am trying to get all filenames from the files inside a zip file. It all works perfectly until the zip file contains another zip file and I try to get the included file names from the included zip as well.
I want to get all included filenames without extracting the file.
For some reason it always refuses to open the included zip file, as if it does not recognie it as a zip file.
To make 100% sure it is a zip for testing I simply included the same zip inside the main zip.
While it properly reads the main zipfile it returns false if I want to read the included file.
I have been trying to get this script to work for 3 days now but I keep failing so I decided to see if someone here can help me out with this.
This is the script I am using to read a zipfile contents:
function firstzipper($file) {
global $filesroot, $pagefile;
$zipinc = new ZipArchive();
if ($zipinc->open($file) === TRUE) {
for ($i = 0; $i < $zipinc->numFiles; $i++) {
$filename_full = $zipinc->getNameIndex($i);
$filename = substr($filename_full, strrpos($filename_full, '/') + 1);
if (!is_dir($filename)) {
$filename = filter_var($filename, FILTER_SANITIZE_STRING);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if ($ext == 'zip') {
secondzipper($filesroot.$pagefile.'/'.$filename_full);
}
}
array_push($inc_files_arr,$filename);
}
return $inc_files_arr;
}
}
firstzipper($filesroot.$url);
secondzipper inside the function above is simply the same function, copied and renamed.
The zipfile looks like this:
E:/myfolder/fileserver/temper.zip/myincluded.zip
The function opens temper.zip but returns false on myincluded.zip.
I hope I have included all info needed, if not let me know and I add what else is required.
I'm facing strange problem right now - "filesize(): stat failed for C:\xampp\tmp\php7A38.tmp" exception. The problem occurs when I'm uploading files in my application built with PHP (Laravel).
Before I'm uploading the files onto the server I'm checking size of files like this (this works very well):
for ($i = 0; $i < $filesLength; $i++) {
if(filesize($request['files'][$i]) < 1572865) {
$file = $request['files'][$i];
$filename = $imageNumber.'.'.$request['files'][$i]->extension();
$file = $file->move(public_path().'/app/newsimages/'.$element->id.'/', $filename);
}
}
If I do it like that everything works very well. But the problem is that I have to put this loop in another loop, like this:
foreach($somelement as $element) {
for ($i = 0; $i < $filesLength; $i++) {
if(filesize($request['files'][$i]) < 1572865) {
$file = $request['files'][$i];
$filename = $imageNumber.'.'.$request['files'][$i]->extension();
$file = $file->move(public_path().'/app/newsimages/'.$element->id.'/', $filename);
}
}
}
In addition to that it crashes at the second loop of the foreach loop.
Maybe you have some idea what's wrong in here?
I think this is obvious, in inner loop you move the file, so when you go to next iteration of outer loop file is not there, so for example if you once move the file:
$request['files'][0]
it's not possible to execute:
filesize($request['files'][0])
because this file was moved - it doesn't exist any more.
I am editing a current website right now. I want to change file uploading mechanism from http to ftp. They use File module with Drupal 7. the thing i need is, in a form, when i select which files to upload, how can i get their machine path (e.g. C:\path/to/file.mov)?
I need this path to use in php ftp_nb_put function.
function assets_managed_file_form_upload_submit($form, &$form_state) {
for ($i = 0; $i < $form_state['num_files']; $i++) {
if ($form_state['values']['files_fieldset']['managed_field'][$i] != 0) {
// Make the file permanent.
$file = file_load($form_state['values']['files_fieldset']['managed_field'][$i]);
$file->status = FILE_STATUS_PERMANENT;
$directory = 'private://cubbyhouse/'. $form_state['values']['allowed_user'];
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
$file->uid = $form_state['values']['allowed_user'];
drupal_chmod($file->uri);
file_save($file);
//drupal_set_message(t($debug=print_r($form)));
// Need to add an entry in the file_usage table.
file_usage_add($file, 'assets', 'image', 1);
drupal_set_message(t("Your file has been uploaded!"));
}
}
}
Right now this is how they handle file submitting
If I have a file called file.html how do i make 10 clones of this file via PHP such that they are renamed file1....file10?
$filename = 'file.html'
$copyname = 'file2.html'
if ($file = #fopen($copyname, 'x')) {
// We've successfully created a file, so it's ours. We'll close
// our handle.
if (!#fclose($file)) {
// There was some problem with our file handle.
return false;
}
// Now we copy over the file we created.
if (!#copy($filename, $copyname)) {
// The copy failed, even though we own the file, so we'll clean
// up by itrying to remove the file and report failure.
unlink($copyname);
return false;
}
return true;
}
Small file approach: this allows you to do something with the contents of the file before saving it:
$text = file_get_contents('file.html');
for($i = 0; $i < 100; $i++) {
file_put_contents('file'.$i.'.html', $data);
}
Bigger files approach: this does not allow you to access the contents of the file before saving it, it only tells the underlying OS to make the copy (equivalent to a linux bash command of cp file.html file1.html):
for($i = 0; $i < 100; $i++) {
copy('file.html', 'file'.$i.'.html');
}
Just run your code in a loop:
$filename = 'file.html'
for($i=1; $i<=10; $i++) {
$copyname = "file$i.html";
copy($filename, $copyname);
}
Feel free to add error checking and handling.
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.