Home > Article > Backend Development > About directory operations in PHP
This article mainly introduces PHP directory operations. It summarizes and analyzes PHP's related functions and usage skills for common operations such as directory reading, traversal, and closing in the form of examples. Friends in need can refer to it
The example in this article summarizes the PHP directory operation method. Share it with everyone for your reference, the details are as follows:
Directory operation
New directory: mkdir (path, permissions, recursive creation)
Delete directory: rmdir()
Move (rename): rename()
Get directory content:
//Open directory
Directory handle = opendir()
//Read directory
File name = readdir(directory handle)
Read the file names in sequence and move the file handle pointer downward at the same time. If it cannot be read, return false
//Close the directory
closedir()
Recursively read the directory content:
<?php showDir('../../file'); function showDir($path,$dep=0){ $pos = opendir($path); while(false!==$file=readdir($pos)){ if($file=='.'||$file=='..') continue; echo str_repeat(" ",$dep*4),$file.'</br>'; if(is_dir($path.'/'.$file)){ $func = __FUNCTION__; $func($path.'/'.$file,$dep+1); } } }
The running effect is as follows:
<?php $res = showDir('../../file'); echo '<pre class="brush:php;toolbar:false">'; print_r($res); function showDir($path){ $pos = opendir($path); $next = array(); while(false!==$file=readdir($pos)){ if($file=='.'||$file=='..') continue; $fileinfo = array(); $fileinfo['name'] = $file; if(is_dir($path.'/'.$file)){ $fileinfo['type'] = 'dir'; $func = __FUNCTION__; $fileinfo['next'] = $func($path.'/'.$file); }else{ $fileinfo['type'] = 'file'; } $next[] = $fileinfo; } closedir($pos); return $next; }
The running effect diagram is as follows:
Recursively delete the directory:
<?php showDir('../../file/sim'); function showDir($path,$dep=0){ $pos = opendir($path); while(false!==$file=readdir($pos)){ if($file=='.'||$file=='..') continue; // echo str_repeat(" ",$dep*4),$file.'</br>'; if(is_dir($path.'/'.$file)){ $func = __FUNCTION__; $func($path.'/'.$file,$dep+1); }else{ unlink($path.'/'.$file); } } rmdir($path); closedir($pos); }
Directory file encoding problem:
Convert operating system encoding to response data encoding when displaying
windows For gbk, the project utf-8
iconv('gbk',utf-8',file);
code address exists in Chinese: it needs to be converted to system encoding
iconv(utf-8','gbk',file);
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About the analysis of php_pdo preprocessing statements
About PHP’s linked list operation
The above is the detailed content of About directory operations in PHP. For more information, please follow other related articles on the PHP Chinese website!