I'm using the following function, to find files with specific file extensions within a given folder and all subfolders:
function FindVideoFiles($startfolder,$specificextensions){
$it = new RecursiveDirectoryIterator($startfolder);
foreach( new RecursiveIteratorIterator($it) as $file) {
if (in_array(strtoupper(substr($file, strrpos($file, '.') + 1)), $specificextensions)) {
$files[]=array('nomedapasta'=>pathinfo($file,PATHINFO_DIRNAME));
}
}
return $files;
}
$specificextensions
is an array with avi
,mkv
and mp4
as values.
$startfolder
is a string with /mnt/HD1_4TB/refazer/A View to a Kill
as value.
When I try to run the function, it throws me an error saying:
failed to open dir: No such file or directory.
The weirdest thing is, if I change the $starfolder
variable to /mnt/HD1_4TB/refazer
, the function works and return the files inside the folder "A View to a Kill" (even with spaces in folder name).
If i rename the folder "A View to a Kill" to "AViewtoaKill" and change the $startfolder
variable to /mnt/HD1_4TB/refazer/AViewtoaKill
, the function also work.....
so..... I think that my problem is the spaces in the folder name.
Can someone help me on how I can solve this problem without removing the spaces in the folder name?
Thanks
My Answer:
$file->getPath(), 'nomearquivo'=>$file->getFilename());_ }_ }_ return $files;_ }_ $specificextensions=array('MP4','AVI','MKV');_ $startfolder='C:\Users\Username\Videos';_ $videoFiles=FindVideoFiles($startfolder,$specificextensions);_ print_r($videoFiles);_?>
The issue with spaces in folder names can be resolved by using the `realpath()` function in PHP. This function resolves any symbolic links and references to the actual path of the file or directory.
You can modify your code as follows to use `realpath()`:
php
function FindVideoFiles($startfolder, $specificextensions){
$startfolder = realpath($startfolder);
$it = new RecursiveDirectoryIterator($startfolder);
foreach(new RecursiveIteratorIterator($it) as $file) {
if (in_array(strtoupper(substr($file, strrpos($file, '.') + 1)), $specificextensions)) {
$files[] = array('nomedapasta' => $file->getPath(), 'nomearquivo' => $file->getFilename());
}
}
return $files;
}
$specificextensions = array('MP4', 'AVI', 'MKV');
$startfolder = 'C:\Users\Username\Videos';
$videoFiles = FindVideoFiles($startfolder, $specificextensions);
print_r($videoFiles);
?>
By using `realpath()` on the `$startfolder` variable, you ensure that any spaces or special characters in the folder name are properly resolved, and the function can traverse the directory structure correctly.
Rate this post
3 of 5 based on 2008 votesComments