Read file inside ZIP subdirectory with PHP - php

I want to read a file inside two zip folders...
My tree:
main_zip_folder
-second_zip_folder
--file_to_read.xml
It's simple to enter in the first_zip_folder and list all the files persent in this folder. I'm using this example:
//create a ZipArchive instance
$zip = new ZipArchive;
//open the archive
if ($zip->open('data/main_zip_folder.zip') === TRUE) {
//iterate the archive files array and display the filename or each one
for ($i = 0; $i < $zip->numFiles; $i++) {
echo 'Filename: ' . $zip->getNameIndex($i) . '<br />';
}
} else {
echo 'Failed to open the archive!';
}
My problem is how to enter in the second_zip_folder to list the files present on it, and open the file_to_read.xml?

I hope it can be help you, This code below help you for reading to zip files or more
<?php
$za = new ZipArchive();
$files = array('zip1.zip', 'zip2.zip');
//$za->open('zip1.zip', 'zip2.zip');
foreach ($files as $fil){
$za->open($fil);
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
print_r( basename( $stat['name'] ) . PHP_EOL . '<br>');
}
}
?>

Related

how to make an array of files which are part of a .zip file

i am trying to make an array of files which are part of a .zip file.
In the .zip file are 2 files: image1.jpg and image2.jpg
$zip = new ZipArchive;
if ($zip->open($_POST['extractfile']) === TRUE) {
$unzipped = 0;
$fails = 0;
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$path_info = pathinfo($zip->getNameIndex($i));
$ext = $path_info['extension'];
$total ++;
echo $zip->getNameIndex($i);
The echo outputs only the first file: image1.jpg
How can i make an array of the files which are in the .zip file so that i can use a foreach loop like below:
foreach($extractfiles as $extractfile) {
echo $extractfile;
}
To the second part
<?php
$zip = new ZipArchive;
$extractfiles = [];
if ($zip->open($_POST['extractfile']) === TRUE) {
$unzipped = 0;
$fails = 0;
$total = 0;
for ($i = 0; $i < $zip->numFiles; $i++) {
$path_info = pathinfo($zip->getNameIndex($i));
$ext = $path_info['extension'];
$total ++;
echo $zip->getNameIndex($i);
$extractfiles[] = $zip->getNameIndex($i);
}
}
foreach($extractfiles as $extractfile) {
echo $extractfile . "<br>" . PHP_EOL;
}

How to check if zip file contains all images file without unzipping on server

I want to check if all files in zip are images or not, till now i have come up with this solution
$zip = new ZipArchive;
$res = $zip->open('CQN.zip');
if ($res) {
$legitImage=explode('.',$zip->statIndex(0)['name']);
if($legitImage[1] !='jpg')
{
// just stop processing
}
}
I just want to loop every file in zip for images, if image is not found than just echo the error
<?php
$za = new ZipArchive();
$za->open('theZip.zip');
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$ext = pathinfo(( basename( $stat['name'] ) . PHP_EOL ), PATHINFO_EXTENSION);
echo $ext;
echo "<br>";
}
?>
This I'm adding array of $ext from FOR loop, take array ouside loop and you can manipulate with that array depend what you wont.
<?php
$array = array();
$za = new ZipArchive();
$za->open('theZip.zip');
for( $i = 0; $i < $za->numFiles; $i++ ){
$stat = $za->statIndex( $i );
$ext = pathinfo(( basename( $stat['name'] ) . PHP_EOL ), PATHINFO_EXTENSION);
$array[] = $ext;
}
print "For: ".count($array)."<br />";
print_r($array);
foreach ($array as $value) {
echo $value . "<br />";
}
?>

Exclude files with diffrent extension on count of files in a folder with php codigniter ? count(* formats,except this format(webm))

I want to get number of video files in a folder suppose .mp4,.mp3,.flv..etc extension and exclude files like .webm extension.How to do this with php condeigniter?
Write a custom function like this
function getCount(){
$overAllCount = 0;
$directory = base_url().'uploads';
$mp4count = glob($directory . '*.mp4');
$mp3count = glob($directory . '*.mp3');
$flvcount = glob($directory . '*.flv');
if ( $mp4count !== false )
{
$filecount = count( $mp4count );
$overAllCount += $filecount;
}
if ( $flvcount !== false )
{
$filecount = count( $flvcount );
$overAllCount += $filecount;
}
if ( $mp3count!== false )
{
$filecount = count( $mp3count);
$overAllCount += $filecount;
}
return $overAllCount;
}

how to prevent extracting a php file from zip

i am using this piece of code to unzip a .zip file
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
$zip->extractTo('/my/destination/dir/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
Lets say: there is a .php file in the .zip and i do not want a .php file to be extracted. How can i prevent that?
You can try something like this for PHP >= 5.5:
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
if( pathinfo($zip->getNameIndex($i)['extension'] != "php")){
$zip->extractTo('/my/destination/dir/', $zip->getNameIndex($i));
}
}
$zip->close();
}
Or this for PHP < 5.5:
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$path_info = pathinfo($zip->getNameIndex($i));
$ext = $path_info['extension'];
if( $ext != "php")){
$zip->extractTo('/my/destination/dir/', $zip->getNameIndex($i));
}
}
$zip->close();
}
The only difference between the two is the pathinfo function. Both will loop all files inside the zip file and, if the file extension isn't php, extracts it to /my/destination/dir/.
$zip= new ZipArchive;
if($zip->open('test.zip') === TRUE){
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = pathinfo($zip->getNameIndex($i));
$fileinfo = $filename['extension'];
if($fileinfo!="php"){
$zip->extractTo('extract/',$zip->getNameIndex($i));
}
$zip->close();
}

How to list files and folder in a dir (PHP) [duplicate]

This question already has answers here:
Deep recursive array of directory structure in PHP
(6 answers)
Closed 9 years ago.
Hi I am trying to show all files and folders in a dir with php
e.g
Dir: system/infomation/
Folder - User
Files From User - User1.txt
Files From User - User2.txt
Files From User - User3.txt
Files From User - User4.txt
Folder - Players
Files From Players - Player1.txt
Files From Players - Player2.txt
Files From Players - Player3.txt
Files From Players - Player4.txt
Can someone lead me down the right street please
Thank You
PHP 5 has the RecursiveDirectoryIterator.
The manual has a basic example:
<?php
$directory = '/system/infomation/';
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid()) {
if (!$it->isDot()) {
echo 'SubPathName: ' . $it->getSubPathName() . "\n";
echo 'SubPath: ' . $it->getSubPath() . "\n";
echo 'Key: ' . $it->key() . "\n\n";
}
$it->next();
}
?>
Edit -- Here's a slightly more advanced example (only slightly) which produces output similar to what you want (i.e. folder names then files).
// Create recursive dir iterator which skips dot folders
$dir = new RecursiveDirectoryIterator('./system/information',
FilesystemIterator::SKIP_DOTS);
// Flatten the recursive iterator, folders come before their files
$it = new RecursiveIteratorIterator($dir,
RecursiveIteratorIterator::SELF_FIRST);
// Maximum depth is 1 level deeper than the base folder
$it->setMaxDepth(1);
// Basic loop displaying different messages based on file or folder
foreach ($it as $fileinfo) {
if ($fileinfo->isDir()) {
printf("Folder - %s\n", $fileinfo->getFilename());
} elseif ($fileinfo->isFile()) {
printf("File From %s - %s\n", $it->getSubPath(), $fileinfo->getFilename());
}
}
//path to directory to scan
$directory = "../data/team/";
//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
//print each file name
foreach($texts as $text)
{
echo $text;
}
You can use:
foreach (new DirectoryIterator("./system/information/") as $fn) {
print $fn->getFilename();
}
You'll have to use it twice for each subdir, Players and User.
LIST FILES IN FOLDER - 1 solution
<?php
// open this directory
$myDirectory = opendir(".");
// get each entry
while($entryName = readdir($myDirectory)) {
$dirArray[] = $entryName;
}
// close directory
closedir($myDirectory);
// count elements in array
$indexCount = count($dirArray);
Print ("$indexCount files<br>\n");
// sort 'em
sort($dirArray);
// print 'em
print("<TABLE border=1 cellpadding=5 cellspacing=0 class=whitelinks>\n");
print("<TR><TH>Filename</TH><th>Filetype</th><th>Filesize</th></TR>\n");
// loop through the array of files and print them all
for($index=0; $index < $indexCount; $index++) {
if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
print("<TR><TD>$dirArray[$index]</td>");
print("<td>"); print(filetype($dirArray[$index])); print("</td>");
print("<td>"); print(filesize($dirArray[$index])); print("</td>");
print("</TR>\n");
}
}
print("</TABLE>\n");
?>
2 solution
<?PHP
# The current directory
$directory = dir("./");
# If you want to turn on Extension Filter, then uncomment this:
### $allowed_ext = array(".sample", ".png", ".jpg", ".jpeg", ".txt", ".doc", ".xls");
## Description of the soft: list_dir_files.php
## Major credits: phpDIRList 2.0 -(c)2005 Ulrich S. Kapp :: Systemberatung ::
$do_link = TRUE;
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING
# # #
function dir_list($dir){
$i=0;
$dl = array();
if ($hd = opendir($dir)) {
while ($sz = readdir($hd)) {
if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;
}
closedir($hd);
}
asort($dl);
return $dl;
}
if ($sort_how == 0) {
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return -1;
else return 1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return -1;
else return 1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return -1;
else return 1;
}
}else{
function compare0($x, $y) {
if ( $x[0] == $y[0] ) return 0;
else if ( $x[0] < $y[0] ) return 1;
else return -1;
}
function compare1($x, $y) {
if ( $x[1] == $y[1] ) return 0;
else if ( $x[1] < $y[1] ) return 1;
else return -1;
}
function compare2($x, $y) {
if ( $x[2] == $y[2] ) return 0;
else if ( $x[2] < $y[2] ) return 1;
else return -1;
}
}
##################################################
# We get the information here
##################################################
$i = 0;
while($file=$directory->read()) {
$file = strtolower($file);
$ext = strrchr($file, '.');
if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
{
// dump
}
else {
$temp_info = stat($file);
$new_array[$i][0] = $file;
$new_array[$i][1] = $temp_info[7];
$new_array[$i][2] = $temp_info[9];
$new_array[$i][3] = date("F d, Y", $new_array[$i][2]);
$i = $i + 1;
}
}
$directory->close();
##################################################
# We sort the information here
#################################################
switch ($sort_what) {
case 0:
usort($new_array, "compare0");
break;
case 1:
usort($new_array, "compare1");
break;
case 2:
usort($new_array, "compare2");
break;
}
###############################################################
# We display the infomation here
###############################################################
$i2 = count($new_array);
$i = 0;
echo "<table border=1>
<tr>
<td width=150> File name</td>
<td width=100> File Size</td>
<td width=100>Last Modified</td>
</tr>";
for ($i=0;$i<$i2;$i++) {
if (!$do_link) {
$line = "<tr><td align=right>" .
$new_array[$i][0] .
"</td><td align=right>" .
number_format(($new_array[$i][1]/1024)) .
"k";
$line = $line . "</td><td align=right>" . $new_array[$i][3] . "</td></tr>";
}else{
$line = '<tr><td align=right><A HREF="' .
$new_array[$i][0] . '">' .
$new_array[$i][0] .
"</A></td><td align=right>";
$line = $line . number_format(($new_array[$i][1]/1024)) .
"k" . "</td><td align=right>" .
$new_array[$i][3] . "</td></tr>";
}
echo $line;
}
echo "</table>";
?>
use this function http://www.codingforums.com/showthread.php?t=71882
function getDirectory( $path = '.', $level = 0 ){
$ignore = array( 'cgi-bin', '.', '..' );
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$dh = #opendir( $path );
// Open the directory to the handle $dh
while( false !== ( $file = readdir( $dh ) ) ){
// Loop through the directory
if( !in_array( $file, $ignore ) ){
// Check that this file is not to be ignored
$spaces = str_repeat( ' ', ( $level * 4 ) );
// Just to add spacing to the list, to better
// show the directory tree.
if( is_dir( "$path/$file" ) ){
// Its a directory, so we need to keep reading down...
echo "<strong>$spaces $file</strong><br />";
getDirectory( "$path/$file", ($level+1) );
// Re-call this same function but on a new directory.
// this is what makes function recursive.
} else {
echo "$spaces $file<br />";
// Just print out the filename
}
}
}
closedir( $dh );
// Close the directory handle
}
and call the function like that
getDirectory( "." );
// Get the current directory
getDirectory( "./files/includes" );
// Get contents of the "files/includes" folder
You may use Directory Functions: http://php.net/manual/en/book.dir.php
Simple example from opendir() function description:
<?php
$dir_path = "/path/to/your/dir";
if (is_dir($dir_path)) {
if ($dir_handler = opendir($dir_path)) {
while (($file = readdir($dir_handler)) !== false) {
echo "filename: $file : filetype: " . filetype($dir_path . $file) . "\n";
}
closedir($dir_handler);
}
}
?>
Use glob. There are comprehensive guide how to open all files from dir:
PHP: Using functional programming for listing files and directories
Use the Dir class or opendir() and readdir() in a recursive function.
http://www.php.net/manual/en/class.dir.php
http://ch2.php.net/manual/en/function.opendir.php
http://ch2.php.net/manual/en/function.readdir.php
I've found in www.laughing-buddha.net/php/lib/dirlist/ a function that returns an array containing a list of a directory's contents.
Also look at php.net http://es.php.net/manual/es/ref.filesystem.php where you'll find additional functions for working with files in php.
Have a look at building a simple directory browser using php RecursiveDirectoryIterator
Also, as you mentioned you want to list you can also look at some ready made libraries that create file/folder explorers e.g.:
http://www.evoluted.net/thinktank/web-development/php-directory-listing-script
If you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = #opendir($root . $path) or die("Unable to open $path");

Categories