I have a problem. I want to output all file names that have an extension .mp4. The following code could make it, but it only outputs from one directory.
<?php
if ($handle = opendir('/media/AB12-34/DCIM/100DCIM')) {
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'mp4')
{
$thelist .= '<p><td><option value="'.$file.'">'.$file. '</option></td>';
}
}
closedir($handle);
I want the script to output all .mp4 files from all directories that are in /media/AB*/DCIM/100DCIM
(please note the star) directory. Is there any way of doing this using opendir
command? Tried with * but it was not working.
Using PHP5's in-built RecursiveDirectoryIterator something like:
<?php
/**
* RecursiveDirectoryIterator function to get media.
*
* @param string $base_dir
* @param array $extentions
* @return array
*/
function get_media($base_dir, $extentions = array('mp4')) {
if(!file_exists($base_dir)) return array();
$extensions = implode('|', $extentions);
$directory = new RecursiveDirectoryIterator($base_dir);
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
$ret = array();
foreach ($regex as $filename=>$object) {
$ret[] = $filename;
}
return $ret;
}
//print_r( get_media('/media/', array('mp4')) );
$thelist = '<select size="1" name="?">';
foreach (get_media('/media/', array('mp4')) as $file)
{
$thelist .= '<option value="'.$file.'">'.$file.'</option>';
}
$thelist .= '</select>';
echo $thelist;
?>
Edit (added time, see comment):
As you basically have the full path to the file, you could add filectime($filename);
within the iterator function or add it outside when doing the display loop, below is doing it inside the function.
<?php
/**
* RecursiveDirectoryIterator function to get media.
*
* @param string $base_dir
* @param array $extentions
* @return array
*/
function get_media($base_dir, $extentions = array('mp4')) {
if(!file_exists($base_dir)) return array();
$extensions = implode('|', $extentions);
$directory = new RecursiveDirectoryIterator($base_dir);
$iterator = new RecursiveIteratorIterator($directory);
$regex = new RegexIterator($iterator, "/^.+\.$extensions$/i", RecursiveRegexIterator::GET_MATCH);
$ret = array();
$i = 0;
foreach ($regex as $filename=>$object) {
$ret[$i]['filename'] = $filename;
$ret[$i]['filetime'] = filectime($filename);
$i++;
}
return $ret;
}
//print_r( get_media('/media/', array('mp4')) );
$thelist = '<select size="1" name="?">';
foreach (get_media('/media/', array('mp4')) as $file)
{
$thelist .= '<option value="'.$file['filename'].'">'.$file['filename'].' - '.date("F j, Y, g:i a",$file['filetime']).'</option>';
}
$thelist .= '</select>';
echo $thelist;
?>