Amir Heshmati
Amir Heshmati

Reputation: 648

Listing directory on a server using php

I need to list a set directories on server using a php script that is also on the server. Here is my folder structure on the server: (ftp)

1

and this is the code that is written in listDirectory.php (I need to know what are the sub-directories of /public_html/stickers/ and how many file exist in each of those sub-directory) I know i can hard-code it but i need a dynamic approach as the files will change a lot.

<html>
<title>Directories</title>
<body>
    <?php
        $directory = $_SERVER['DOCUMENT_ROOT'] . '/stickers/';
        echo "<p>$directory</p>";
        
        $sticker_directories =  array(scandir($directory));
        
        echo "<p>Number of subdirs at $directory :". count($sticker_directorie) . "</p>";
        
        foreach ($sticker_directories as $dir){
            $working_dir = $directory.$dir;
            echo "<p>$working_dir</p>"; 
            if (is_dir($working_dir)){
                
                echo "<p>$working_dir" . count(scandir($working_dir)) . "</p>";
            }
        }   
    ?>
</body>
</html> 

and this is the output:

/home/u826063014/public_html/stickers/

Number of subdirs at /home/u826063014/public_html/stickers/ :0

/home/u826063014/public_html/stickers/Array

Which is not the result i was expecting. what am i doing wrong?

(I'm totally new to all this)

Upvotes: 0

Views: 2013

Answers (1)

u_mulder
u_mulder

Reputation: 54841

First of all scandir already returns array. There's no need to use array.

$sticker_directories = scandir($directory);

// `scandir` returns both files and subdirs. So, this string is not true
echo "<p>Number of subdirs at $directory :". count($sticker_directories) . "</p>";
//                                                                    ^ s missed

After that all should be fine.

Upvotes: 1

Related Questions