Home  >  Article  >  PHP directory traversal operation

PHP directory traversal operation

无忌哥哥
无忌哥哥Original
2018-06-28 11:01:272396browse

* Directory traversal operation:

* 1. Traditional process functions: opendir(), readdir(), closedir()

* 2. Directory scanner: scandir()

* The first way: traditional directory function

* The first step: opendir('directory') opens the directory, returns the resource successfully, returns false on failure

* The second step : readdir($dir) reads the directory content, Shigong returns the file name, and returns false on failure

* The third step: closedir($dir) closes the current directory

$dir = opendir('../0418') or die('打开失败');
// $dir = opendir('./') or die('打开失败');  //.或./当前目录
while (false != ($file = readdir($dir))) {
// print $file."<br>";
// print nl2br($file."\n");
if ($file != "." && $file != "..") {      
print $file."<br>";
     }
}
closedir($dir);
echo &#39;<hr>&#39;;

* The second type Method: Save the directory contents into an array for traversal

* The first step: scandir($dir) converts the directory into an array and saves it

* The second step: Traverses the directory array

//Read the contents of a directory into an array:

$fileArr = scandir(&#39;../0417/&#39;);
// print_r($fileArr);
foreach ($fileArr as $file) {
if ($file != "." && $file != "..") {
        echo "$file<br>";
     }
}

//Explanation: If you want to recurse all directories, you need to write a custom function to solve the problem. We introduce a more convenient recursive traversal technology.

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