Thursday, 9 June 2016

How to list files in directory in PHP?

How to list files in directory  by Group files?

Display the list of files in directory.
Files will be list in Group by extension like PDF, JPG and PHP etc.
Also list the files with sizes in Kilo Bytes.


Code Snippet



$path    = 'E:\wamp\www\project\public_html\images';
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));
$groupFiles=array();
foreach($files as $file){    
    $keyName=$extension = pathinfo($file, PATHINFO_EXTENSION);
    if(empty($extension)){
        $keyName='directory';
    }
    $keyName=strtolower($keyName);
    $groupFiles[$keyName][]=$file;    
}
echo '<table border=1>';
foreach($groupFiles as $fileExtention=>$files){
    echo "<tr>";
    echo "<td><h3>{$fileExtention}</h3></td>";
    echo "<td>";
    foreach($files as $file){
        $fileSize= filesize($path.'\\'.$file);
        echo $file.' (<b>'.(number_format($fileSize/1024,0)).'</b> KB)';echo "<br >";
    }
    echo "</td>";
    echo "</tr>";
}
echo '</table>';



Output


jpg

TALENT-LOGO.JPG (41 KB)
backImg.jpg (1,667 KB)
backImg1.jpg (490 KB)
backImg2.jpg (336 KB)
backImg3.jpg (51 KB)
default.jpg (2 KB)
drexel-bg.jpg (99 KB)
flashUpdate.jpg (26 KB)
powerpitchlogo.jpg (23 KB)
robert-bg.jpg (100 KB)
smlogoborder.jpg (29 KB)
videoThumb.jpg (60 KB)

png

assets-tour-page.png (15 KB)
buttons-navigation.png (16 KB)
chat.png (267 KB)
clock-icon.png (5 KB)
close.png (2 KB)
columbia-bg.png (21 KB)
email-share.png (3 KB)
facebook-icon-chat.png (1 KB)
facebook-share-button.png (14 KB)
fb-login.png (2 KB)
globeIcon.png (2 KB)
icons_sprite.png (13 KB)
img_close.png (2 KB)
imsa-footer.png (12 KB)
imsa-header.png (11 KB)
island.png (65 KB)
large-be-right-back-final.png (21 KB)
logo-power-grey.png (4 KB)
logo-power-white.png (3 KB)
new-geo-logo.png (6 KB)
pause-image.png (9 KB)
playButtonThumb.png (6 KB)
playButtonThumb1.png (9 KB)
please-stand-by.png (1,076 KB)
power-geo-logo.png (6 KB)
powered-by-georama-white.png (2 KB)
powered-by-georama.png (2 KB)
rsvp.png (22 KB)
scroll-icons.png (2 KB)
sendMsgBtn.png (2 KB)
shareIcon.png (1 KB)
top-down-arrow.png (1 KB)
tw-sign-up.png (3 KB)
tweetbutton.png (7 KB)
twitter-icon-chat.png (1 KB)
verShadow.png (2 KB)
virtual-tour-assets.png (18 KB)

gif

btn_buynowCC_LG.gif (4 KB)
clear.gif (1 KB)
loading.gif (4 KB)

directory

email (4 KB)
fileUpload (0 KB)
guides (0 KB)
ohio (4 KB)
sign-in-forms (4 KB)
sign-up-forms (4 KB)
survey (4 KB)
tourImage (0 KB)
tours (0 KB)