Home >Backend Development >PHP Tutorial >Example usage of php scandir() function to exclude specific directories
scandir() returns an array of files and directories in the specified directory. If successful, return an array of files and directories. Returns FALSE on failure. If directory is not a directory, an E_WARNING level error is thrown.
Syntax
scandir(directory,sorting_order,context);
Parameters | Description |
---|---|
directory | Required. Specifies the directories to be scanned. |
sorting_order | ##Optional. Specify the order of sorting. The default is 0, indicating ascending alphabetical order. If set to SCANDIR_SORT_DESCENDING or 1, it means sorting in descending alphabetical order. If set to SCANDIR_SORT_NONE, returns unsorted results. |
context | Optional. Specifies the environment for directory handles.context is a set of options that modify the behavior of directory streams. |
The code is as follows:
<?php print_r(scandir('test_directory')); ?>The output is as follows:
Array ( [0]=>. [1]=>.. [2]=>1.txt [3]=>2.txt )In most cases, only this directory is needed The file list array is as follows:
Array ( [0]=>1.txt [1]=>2.txt )It is usually solved by excluding "." or ".." array items:
The code is as follows:
<?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 one This method uses the
array_difffunction to eliminate the array obtained by executing the scandir function: The code is as follows:
<?php $directory='/path/to/my/directory'; $scanned_directory=array_diff(scandir($directory),array('..','.')); ?>Normally code management will generate. svn file, or .htaccess and other files that restrict directory access permissions. So it is more convenient to filter through the array_diff function.
The above is the detailed content of Example usage of php scandir() function to exclude specific directories. For more information, please follow other related articles on the PHP Chinese website!