Search code examples
phpscandir

How to get only video files from folder directory of all files in php?


I have some videos,images and text files in "uploads/video/" dir. Here i am getting all the files using scandir but I want only videos from that folder.

Sample code :

$video_dir    = 'uploads/video/';
$video_array = scandir($video_dir);

unset($video_array[0]);
unset($video_array[1]);

echo "<pre>";
print_r($video_array);
echo "</pre>";

Getting Result :

Array ( [2] => ADD.mp4 [3] => COO_Notes.txt [4] => Carefree.mp3 [5] => Circus Tent.mp3 [6] => Phen.mp4 [7] => REM.mp4 [8] => images (9).jpg [9] => images.jpg [10] => test.php ) 

I need only video files. Remove the text,mp3,jpg,etc files:

Array ( [2] => ADD.mp4  [6] => Phen.mp4 [7] => REM.mp4) 

Thanks for your updates.


Solution

  • You can use glob():

    <?php
    foreach (glob("*.mp4") as $filename) {
        echo "$filename - Size: " . filesize($filename) . "\n";
    }
    # or:
    $video_array = glob("*.mp4");
    ?>
    

    In order to get multiple formats, simply put the extensions in curly braces and add the parameter GLOB_BRACE:

    $video_array = glob('uploads/video/{*.mp4,*.flv,*.mov}', GLOB_BRACE);
    

    See it on PHP.net here.