Exclude specific directories using PHP function scandir
- 2021-06-29 10:25:54
- OfStack
The scandir() function returns an array containing files and directories in the specified path.As follows:
Example:
<?php
print_r(scandir('test_directory'));
?>
Output:
Array
(
[0]=>.
[1]=>..
[2]=>1.txt
[3]=>2.txt
)
In most cases, you only need an array of file lists for that directory, as follows:
Array
(
[0]=>1.txt
[1]=>2.txt
)
1 is usually solved by excluding an array item of'. 'or'.':
<?php
functionfind_all_files($dir)
{
$root = scandir($dir);
foreach($rootas$value)
{
if($value === '.' || $value === '..'){
continue;
}
if(is_file("$dir/$value")){
$result[] = "$dir/$value";
continue;
}
foreach(find_all_files("$dir/$value")as$value)
{
$result[] = $value;
}
}
return$result;
}
?>
Another method, using array_diff function, eliminates the array that the scandir function executes:
<?php
$directory='/path/to/my/directory';
$scanned_directory=array_diff(scandir($directory),array('..','.'));
?>
Usually code management produces.svn files, or.htaccess files that restrict directory access.So by array_The diff function is more convenient to filter.