问题
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.
回答1:
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.
回答2:
I believe the function pathinfo
should help you out.
http://php.net/manual/en/function.pathinfo.php
<?php
$videos = array();
$video_ext = array('mp4', 'mpeg');
foreach ($video_array as $path) {
if (in_array(pathinfo($path, PATHINFO_EXTENSION), $video_ext)) {
//less general, but will work if you know videos always end in mp4
//if (pathinfo($path, PATHINFO_EXTENSION) == "mp4") {
$videos[] = $path;
}
}
回答3:
You may check file type with mime_content_type
: http://php.net/manual/en/function.mime-content-type.php.
Assume this will be something like:
$videos = array();
$dir = 'uploads';
$files = scandir($dir);
foreach($files as $file) {
$filepath = $dir . '/' . $file;
if(is_file($filepath)) {
$contentType = mime_content_type($filepath);
if(stripos($contentType, 'video') !== false) {
$videos[] = $file;
}
}
}
Also this may be not very fast and perhaps will not detect all possible (strange) video files (as it uses magic.mime
). But this may work without array of file extensions and also will look at file itself rather than filename.
来源:https://stackoverflow.com/questions/34926245/how-to-get-only-video-files-from-folder-directory-of-all-files-in-php