Skip to content

PHP get files in folder

Solution One:

<?php
$dir = "uplaod/"; // Sort in ascending order - this is default
$a = scandir($dir); // Sort in descending order //
$b = scandir($dir,1);
print_r($a);
?>

Solution Two:

<?php
/**
You can get files in a folder and subfolders in php
by using the recursiveDirectoryIterator

Documentation: http://php.net/manual/en/class.recursivedirectoryiterator.php
*/

$directory = new RecursiveDirectoryIterator(DIR, FilesystemIterator::SKIP_DOTS);
$iterator = new RecursiveIteratorIterator($directory);
$files = new RegexIterator($iterator, '/^.+.php$/i', RegexIterator::GET_MATCH);

$result = array();
foreach($files as $file) {
$result[] = $file[0];
}

echo json_encode($result);

Solution Three:

<?php

/*
 * get files in folder with documentation.
 */

$dir = './';
$files = array();
$dirHandle = opendir($dir);
while($file = readdir($dirHandle)){
    if($file != '.' && $file != '..'){
        $files[] = $file;
    }
}
closedir($dirHandle);

$arr_file_type = array('zip');

foreach($files AS $file){
    echo '<h3>'.$file.'</h3>';
    $file_parts = pathinfo($file);
    $ext = strtolower($file_parts['extension']);
    if(in_array($ext,$arr_file_type)){
        $type = 'archive';
        $class = 'fa fa-file-zip-o';
    }
    if($type == 'archive'){
        echo '<p>File Type: <i class="'.$class.'"></i> '.$type.'</p>';
    }
    echo '<p>Size: '.filesize($file).' bytes</p>';
    echo '<p>Last Modified: '.date("M j, Y, g:i a", filemtime($file)).'</p>';
    echo '<hr>';
}
?>