Asked  7 Months ago    Answers:  5   Viewed   94 times

I have this code:

$za = new ZipArchive();
$za->open($downloadlink);
echo "Number of files inside Zip = Unknown";
            for( $i = 0; $i < $za->numFiles; $i++ ){
                $stat = $za->statIndex( $i );
                $tounes = array( basename( $stat['name'] ) . PHP_EOL );
                foreach($tounes as $toune) {
                echo $toune;
                }
            }

I want to display the number of files inside the archive before displaying the list. How can i do that ?

 Answers

93

You already have the answer in your for loop:

echo "Number of files inside Zip = ".$za->numFiles;

http://php.net/manual/en/class.ziparchive.php

Friday, May 28, 2021
 
PLPeeters
answered 7 Months ago
54

The problem here is that $zip->addFile is being passed the same two parameters.

According to the documentation:

bool ZipArchive::addFile ( string $filename [, string $localname ] )

filename
The path to the file to add.

localname
local name inside ZIP archive.

This means that the first parameter is the path to the actual file in the filesystem and the second is the path & filename that the file will have in the archive.

When you supply the second parameter, you'll want to strip the path from it when adding it to the zip archive. For example, on Unix-based systems this would look like:

$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
Wednesday, March 31, 2021
 
zhartaunik
answered 9 Months ago
71

Glob returns an array, on error it returns false.

Try this:

$directory = '/var/www/ajaxform/';
$files = glob($directory . '*.jpg');

if ( $files !== false )
{
    $filecount = count( $files );
    echo $filecount;
}
else
{
    echo 0;
}
Wednesday, March 31, 2021
 
Kevin_Kinsey
answered 9 Months ago
27

11 is the constant ZIPARCHIVE::ER_OPEN, which the manual describes with

Can't open file

Note that the manual does not state that stream wrappers may be used.


Please think about using PHP's phar extension - it does what you want, and is well tested.

Saturday, May 29, 2021
 
jakubos
answered 7 Months ago
100

Something has to iterate over all files in the directory, and look at every single file name - whether that's your code or a library routine. So no matter what the specific solution, they will all have roughly the same cost.

If you think it's too much code, and if you don't actually need to search subdirectories recursively, you can use the glob module:

import glob
tifCounter = len(glob.glob1(myPath,"*.tif"))
Sunday, August 1, 2021
 
HMK
answered 4 Months ago
HMK
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share