Categories : PHP

In this article you will learn:

How to List All Files and Directories Requiresively and get as an arrayy

List just all files Requiresively in PHP

List all files and directories in current directory

List just files in current directory PHP CANDIR()

just directories in PHP CANDIR()

How to List All Files and Directories Requiresively and get as an array

Notice : Returns all files and directories widthin a directory REQUIRESIVELY.

<?php

function scan_dir($directory,&$result_array = []){

    $files = array_diff(scandir($directory), array('.', '..'));

    foreach ($files as $file) {

        $result_array[] = $directory . "/" . $file;

        if (is_dir($directory . "/" . $file)) {
            scan_dir($directory . "/" . $file , $result_array);
        }
        
    }

}


$result_array = [];

scan_dir(__DIR__ , $result_array);

print_r($result_array);


List only all files Requiresively in PHP





<?php

function scan_dir($directory,&$result_array = []){

    $files = array_diff(scandir($directory), array('.', '..'));

    foreach ($files as $file) {

        if (is_dir($directory . "/" . $file)) {
            scan_dir($directory . "/" . $file , $result_array);
        }else{
            $result_array[] = $directory . "/" . $file;
        }
        
    }

}


$result_array = [];

scan_dir(__DIR__ , $result_array);

print_r($result_array);




List all files and directories in current directory

<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    echo __DIR__ . "/" . $file;
}

List just files in current directory PHP CANDIR()



<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    //jump if it is not a file
    if(!is_file(__DIR__ . "/" . $file)) continue;
    echo __DIR__ . "/" . $file;
}


List just directories in PHP CANDIR()



<?php

$files = array_diff(scandir(__DIR__), array('.', '..'));

foreach ($files as $file){
    //jump if it is not a file
    if(is_file(__DIR__ . "/" . $file)) continue;
    echo __DIR__ . "/" . $file;
}



Leave a Reply

Your email address will not be published.