Php Zip manipulation - php

I have a zip file.
I need a simple way to read the name of the files from the zip and read the contents of one of the files.
Can this be done directly in memory without saving,opening and reading the files ?

You need to open the archive and then can iterate over the files by index:
$zip = new ZipArchive();
if ($zip->open('archive.zip'))
{
for($i = 0; $i < $zip->numFiles; $i++)
{
echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
}
}
else
{
echo 'Error reading .zip!';
}
To read the content of a single file you can use ZipArchive::getStream($name).
$zip = new ZipArchive();
$zip->open("archive.zip");
$fstream = $zip->getStream("index.txt");
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
Another way to directly do it is using the zip:// stream wrapper:
$file = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
...

Related

Split CSV file into 6 mb files

I am trying to divide CSV file into 6mb files. Following is the code I have tried.
$file = 'upload/L_10001_20200916183801.csv';
$files = SplitCSVBySize($file, 10001);
function SplitCSVBySize($Existingfiles, $AccountId, $splitSize = "") {
$fh = fopen($Existingfiles, 'r');
$headers = fgetcsv($fh);
$files = array();
$filepath = 'upload/' . 'L_' . $AccountId . '_' . date('YmdHis') . '.csv';
$files[] = $filepath;
$currentFile = $filepath;
$outputFile = fopen($filepath, 'w');
fputcsv($outputFile, $headers);
$rows = 0;
while (!feof($fh)) {
if ($row = $rowPri = fgetcsv($fh))
{
if(filesize($filepath) < 6000000){
fputcsv($outputFile, $row);
} else {
fclose($outputFile);
$rows = 0;
$filepath = 'upload/' . 'L_' . $AccountId . '_' . date('YmdHis') . '.csv';
$files[] = $filepath;
$currentFile = $filepath;
$outputFile = fopen($filepath, 'w');
fputcsv($outputFile, $headers);
fputcsv($outputFile, $row);
}
$rows++;
}
}
fclose($outputFile);
fclose($fh);
return $files;
}
Here challenge is I am not able to check filesize because It always returns same size as it was at very first check. Plese help here, what is wrong or any suggestion.
First of all. function filesize (as well as all other derivatives from stat) is cached. That means, once called on some file, its result will remain the same for the same file.
You need to call clearstatcache() prior to calling this function, to clear the cache.
Second. You don't need to call filesize to obtain the size of the opened file.
You can call fstat on the opened file handle and use 'size' item of the returned array . E.g.:
...
$st = filestat($outputFile);
if($st['size'] < 6000000){
...
And at last you don't need to know size of the file, since you have current file position which is, when writing to the file, equals to its size. You can use ftell to obtain that. I.e.
...
if (ftell($outputFile) < 6000000) {
...

How to put multiple photos in a compressed file after downloading php

I have this code which downloads several images from private sites. I want all these images to be placed in a zip file.
how do I do this?
<?php
$num = $_POST['num'];
for ($i=1; $i <= $num ; $i++) {
$url_to_image = $_POST['img'].$i.'.jpg';
$my_save_dir = "manga/" ;
$filename = basename($url_to_image);
$complete_save_loc = $my_save_dir . $filename;
file_put_contents($complete_save_loc,
file_get_contents($url_to_image));
echo $i ."jpg". " /download" . '<br>';
}
?>
You can use the php-ZipArchive class. http://php.net/manual/de/zip.examples.php
If you dont have compiled your php-interpreter with the option --enable-zip you can use otherwise the php shell execution functions (exec, shell_exec, passthru) to use the host-systems zip.
you can try ZipArchive like below
$zip = new ZipArchive();
$my_save_dir = "manga/files.zip";
$zip->open($my_save_dir, ZipArchive::CREATE);
$num = $_POST['num'];
for ($i=1; $i <= $num ; $i++) {
$url_to_image = $_POST['img'].$i.'.jpg';
$download_file = file_get_contents($url_to_image);
$zip->addFromString(basename($url_to_image), $download_file);
}
$zip->close();
echo $my_save_dir;

Extract files in a zip to root of a folder?

I have a zip file uploaded to server for automated extract.
the zip file construction is like this:
/zip_file.zip/folder1/image1.jpg
/zip_file.zip/folder1/image2.jpg
/zip_file.zip/folder1/image3.jpg
Currently I have this function to extract all files that have extension of jpg:
$zip = new ZipArchive();
if( $zip->open($file_path) ){
$files = array();
for( $i = 0; $i < $zip->numFiles; $i++){
$entry = $zip->statIndex($i);
// is it an image?
if( $entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'] ) ){
$f_extract = $zip->getNameIndex($i);
$files[] = $f_extract;
}
}
if ($zip->extractTo($dir_name, $files) === TRUE) {
} else {
return FALSE;
}
$zip->close();
}
But by using the function extractTo, it will extract to myFolder as ff:
/myFolder/folder1/image1.jpg
/myFolder/folder1/image2.jpg
/myFolder/folder1/image3.jpg
Is there any way to extract the files in folder1 to the root of myFolder?
Ideal:
/myFolder/image1.jpg
/myFolder/image2.jpg
/myFolder/image3.jpg
PS: incase of conflict file name I only need to not extract or overwrite the file.
Use this little code snippet instead. It removes the folder structure in front of the filename for each file so that the whole content of the archive is basically extracted to one folder.
<?php
$path = "zip_file.zip";
$zip = new ZipArchive();
if ($zip->open($path) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
copy("zip://".$path."#".$filename, "/myDestFolder/".$fileinfo['basename']);
}
$zip->close();
}
?>
Here: (i tried to manage everything)
$zip = new ZipArchive();
if( $zip->open($file_path) ){
$files = array();
for( $i = 0; $i < $zip->numFiles; $i++){
$entry = $zip->statIndex($i);
// is it an image?
if( $entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'] ) ){
$f_extract = $zip->getNameIndex($i);
$files[] = $f_extract; /* you man want to keep this array (use it to show result or something else) */
if ($zip->extractTo($dir_name, $f_extract) === TRUE) {
$solid_name = basename($f_extract);
if(strpos($f_extract, "/")) // make sure zipped file is in a directory
{
if($dir_name{strlen($dir_name)-1} == "/") $dir_name = substr($dir_name, 0, strlen($dir_name)-1); // to prevent error if $dir_name have slash in end of it
if(!file_exists($dir_name."/".$solid_name)) // you said you don't want to replace existed file
copy($dir_name."/".$f_extract, $dir_name."/".$solid_name); // taking file back to where you need [$dir_name]
unlink($dir_name."/".$f_extract); // [removing old file]
rmdir(str_replace($solid_name, "", $dir_name."/".$f_extract)); // [removing directory of it]
}
} else {
echo("error on export<br />\n");
}
}
}
$zip->close();
}
You can do so by using the zip:// syntax instead of Zip::extractTo as described in the php manual on extractTo().
You have to match the image file name and then copy it:
if ($entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'])) {
copy('zip://' . $file_path . '#' . $entry['name'], '/root_dir/' . md5($entry['name']) . '.jpg');
}
The above replaces your for loop's if statement and makes your extractTo unnecessary. I used the md5 hash of the original filename to make a unique name. It is extremely unlikely you will have any issues with overwriting files, since hash collisions are rare. Note that this is a bit heavy duty, and instead you could do str_replace('/.', '', $entry['name']) to make a new, unique filename.
Full solution (modified version of your code):
<?php
$zip = new ZipArchive();
if ($zip->open($file_path)) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->statIndex($i);
// is it an image?
if ($entry['size'] > 0 && preg_match('#\.(jpg)$#i', $entry['name'])) {
# use hash (more expensive, but can be useful depending on what you're doing
$new_filename = md5($entry['name']) . '.jpg';
# or str_replace for cheaper, potentially longer name:
# $new_filename = str_replace('/.', '', $entry['name']);
copy('zip://' . $file_path . '#' . $entry['name'], '/myFolder/' . $new_filename);
}
}
$zip->close();
}
?>

Read Zip file from URL with PHP

I'm searching for a good solution to read a zip file from an url with php.
I checked the zip_open() function, but i never read anything about reading the file from another server.
Thank you very much
The best way to do that is to copy the remote file in a temporary one:
$file = 'http://remote/url/file.zip';
$newfile = 'tmp_file.zip';
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
Then, you can do whatever you want with the temporary file:
$zip = new ZipArchive();
if ($zip->open($newFile, ZIPARCHIVE::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
This is a basic example:
$url = 'https://my.domain.com/some_zip.zip?blah=1&hah=2';
$destination_dir = '/path/to/local/storage/directory/';
if (!is_dir($destination_dir)) {
mkdir($destination_dir, 0755, true);
}
$local_zip_file = basename(parse_url($url, PHP_URL_PATH)); // Will return only 'some_zip.zip'
if (!copy($url, $destination_dir . $local_zip_file)) {
die('Failed to copy Zip from ' . $url . ' to ' . ($destination_dir . $local_zip_file));
}
$zip = new ZipArchive();
if ($zip->open($destination_dir . $local_zip_file)) {
for ($i = 0; $i < $zip->numFiles; $i++) {
if ($zip->extractTo($destination_dir, array($zip->getNameIndex($i)))) {
echo 'File extracted to ' . $destination_dir . $zip->getNameIndex($i);
}
}
$zip->close();
// Clear zip from local storage:
unlink($destination_dir . $local_zip_file);
}
Download the file contents (possibly with file_get_contents, or copy to put it on your filesystem) then apply the unzip algorithm.

Unzip the file using php (collapses the ZIP file into one Folder)

$file_name = 'New Folder.zip'
$zip = new ZipArchive;
$result = $zip->open($target_path.$file_name);
if ($result === TRUE) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
copy("zip://".$file_name."#".$filename, $target_path.$fileinfo['basename']);
}
}
When i run this code i get this error Warning: copy(zip://New Folder.zip#New Folder/icon_android.png) [function.copy]: failed to open stream: operation failed in...
How can I solve this...
From PHP's doc
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo($your_desired_dir);
$zip->close();
foreach (glob($your_desired_dir . DIRECTORY_SEPARATOR . 'New Folder') as $file) {
$finfo = pathinfo($file);
rename($file, $your_desired_dir . DIRECTORY_SEPARATOR . $finfo['basename']);
}
unlink($your_desired_dir . DIRECTORY_SEPARATOR . 'New Folder');
echo 'ok';
} else {
echo 'failed';
}
Dunno why are you using stream.
copy("zip://".$file_name."#".$filename, $target_path.$fileinfo['basename']);}
correct to
copy("zip://".dirname(__FILE__).'/'.$file_name."#".$filename, $target_path.$fileinfo['basename']);}
Full path need to use zip:// stream
see manual http://php.net/manual/en/book.zip.php
unzip.php (sample code)
// the first argument is the zip file
$in_file = $_SERVER['argv'][1];
// any other arguments are specific files in the archive to unzip
if ($_SERVER['argc'] > 2) {
$all_files = 0;
for ($i = 2; $i < $_SERVER['argc']; $i++) {
$out_files[$_SERVER['argv'][$i]] = true;
}
} else {
// if no other files are specified, unzip all files
$all_files = true;
}
$z = zip_open($in_file) or die("can't open $in_file: $php_errormsg");
while ($entry = zip_read($z)) {
$entry_name = zip_entry_name($entry);
// check if all files should be unzipped, or the name of
// this file is on the list of specific files to unzip
if ($all_files || $out_files[$entry_name]) {
// only proceed if the file is not 0 bytes long
if (zip_entry_filesize($entry)) {
$dir = dirname($entry_name);
// make all necessary directories in the file's path
if (! is_dir($dir)) { pc_mkdir_parents($dir); }
$file = basename($entry_name);
if (zip_entry_open($z,$entry)) {
if ($fh = fopen($dir.'/'.$file,'w')) {
// write the entire file
fwrite($fh,
zip_entry_read($entry,zip_entry_filesize($entry)))
or error_log("can't write: $php_errormsg");
fclose($fh) or error_log("can't close: $php_errormsg");
} else {
error_log("can't open $dir/$file: $php_errormsg");
}
zip_entry_close($entry);
} else {
error_log("can't open entry $entry_name: $php_errormsg");
}
}
}
}
from http://www.java-samples.com/showtutorial.php?tutorialid=985
First thing I would do is this:
echo "FROM - zip://".$file_name."#".$filename;
echo "<BR>TO - " . $target_path.$fileinfo['basename'];
and see what you get
I have used very simple method to do this
system('unzip assets_04_02_2015.zip');

Categories