J
J
Jony13372015-10-04 11:43:08
PHP
Jony1337, 2015-10-04 11:43:08

Script that counts the number of items in a folder?

I have a script that counts the number of items in a folder, the script looks like this:

<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = '50/images/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "$i items";
?>

I put it in the folder 50 and opened it in the browser mysite.ru/50/stat.php
it shows - 0 items
but in the folder 50/images - there are 4 photos

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
index0h, 2015-10-04
@index0h

Don't do it like that, from the word never.
To avoid such garbage:
1. First check if the path is a directory.
2. Then do the actions.
When working with paths, it's best to use global paths.

$path = __DIR__ . '/50/images/';

if (!is_dir($path)) {
    throw new \RuntimeException(sprintf('Incorrect path: %s', $path));
}

$foundFiles = array_diff(scandir($path), ['..', '.']);

// Warning, it could be folders to
echo count($foundFiles);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question