Home >Backend Development >PHP Tutorial >Example usage of php scandir() function to exclude specific directories

Example usage of php scandir() function to exclude specific directories

怪我咯
怪我咯Original
2017-07-10 16:03:182407browse

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);
Optional. Specifies the environment for directory handles.
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 context is a set of options that modify the behavior of directory streams.
Example:

The code is as follows:

<?php
print_r(scandir(&#39;test_directory&#39;));
?>

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 === &#39;.&#39; || $value === &#39;..&#39;){
            
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=&#39;/path/to/my/directory&#39;;
$scanned_directory=array_diff(scandir($directory),array(&#39;..&#39;,&#39;.&#39;));
?>

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn