1

I am running PHP 7.0.22, under LAMP, on two ubuntu 16.04.

My PHP code is as follows

    $str="ls -1 /var/www/dropbox | egrep '*.CEL|*.cel'";
    $result= explode(PHP_EOL, shell_exec($str));
    $fileNames=$result;
    print_r($fileNames);
    echo "<br>";
    $inputFileCount=count($fileNames,1);
    echo "<br>";
    echo "File count:" . print_r($inputFileCount);
    echo "<br>";

I get the following on the screen

Array ( [0] => prefix1.cel [1] => prefix12.cel [2] => ) 

File count:1

It seems to me that the count should be 2.

OtagoHarbour
  • 3,969
  • 6
  • 43
  • 81

3 Answers3

4

Use glob() to get a list of .cel files, i.e.:

$files = glob("/var/www/dropbox/*.cel");
echo count($files)

To loop use:

foreach ($files as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
1

You could also use PHP SPL Iterator classes.

<?php
$folder = '/var/www/dropbox';

// define filtering (match only .cel or .CEL files)
$filter = new \RecursiveCallbackFilterIterator(
    new \RecursiveDirectoryIterator($folder, \FilesystemIterator::SKIP_DOTS), 
    function ($current, $key, $iterator) {
        return strtolower($current->getExtension()) === 'cel';
    }
);

$iterator = new \RecursiveIteratorIterator($filter);

// get count
echo iterator_count($iterator);

// loop over
if (iterator_count($iterator) > 0) {
    foreach ($iterator as $file) {
        echo $file;
    }
}

Slightly more code then glob, but also an option.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
1

ls -l gives you the long listing showing size, permissions, etc. I don't think this is what you want.

Use "\n" as the splitting parameter to split on new lines.

After explode() you want to work with the created array.

One more thing: Please use echo in your code. print_r is for outputting more info about a variable.

$str="ls /var/www/dropbox | egrep '*.CEL|*.cel'";
$result= explode("\n", $str);

foreach($result as $filename) {
    echo $filename . "<br />";
}

$inputFileCount = count($result);
echo "<br>";
echo "File count:" . $inputFileCount;
echo "<br>";
Greg Klaus
  • 109
  • 5