To traverse all the directories in a folder, list all the files inside, PHP itself has a readdir function, but only the current directory, according to this function, I wrote another function to achieve my needs.
| The code is as follows |
Copy Code |
|
Class listdir{
var $depth;
var $dirname;
var $list;
var $tostring;
function Listdir ($dir) {
$this->dirname= $dir;
$this->depth=0;
$this->tostring= "";
}
Save the result in a multidimensional array
function getlist ($dir = "") {
if ($dir = = "") $dir = $this->dirname;
$d = @dir ($dir);
while (false!== ($item = $d->read ()))
{
if ($item! = "." && $item! = "...")
{
$path = $dir. " /". $item;
if (Is_dir ($path)) {
$this->depth+=1;
$this->getlist ($path);
}else{
$this->list[$this->depth][]= $item;
}
}
}
$this->list[$this->depth][' directory ']= $dir;
$this->depth-=1;
$d->close ();
return $this->list;
}
Character channeling results
function ToString ($dir = "") {
if ($dir = = "") $dir = $this->dirname;
$d = @dir ($dir);
$this->tostring.= "
n ";
$this->tostring.= "Directory:" $dir. " n ";
while (false!== ($item = $d->read ()))
{
if ($item! = "." && $item! = "...")
{
$path = $dir. " /". $item;
if (Is_dir ($path)) {
$this->depth+=1;
$this->tostring ($path);
}else{
$this->tostring.= "
- ". $item."
n ";
}
}
}
$this->depth-=1;
$d->close ();
$this->tostring.= "
n ";
return $this->tostring;
}
}
$wapdir = "jquery";
$d =new Listdir ($wapdir);
echo $d->tostring ();
?>
|
To delete an empty directory is simple ~ a
RmDir () function can be done, but to delete a non-empty directory, you will not be able to quickly delete, you must first delete the directory files, but there may be subdirectories in the directory so to be recursive delete ~ here is my example ~
| The code is as follows |
Copy Code |
<? Php
function Deletedir ($dir) {
if (!handle= @opendir ($dir)) {//detects if the directory to open exists
Die ("No such directory");
}
while (False!== ($file =readdir ($handle))) {
if ($file!== "." && $file!== "..") {//Exclude current directory from parent directory
$file = $dir. Directory_separator. $file;
if (Is_dir ($file)) {
Deletedir ($file);
}else{
if (@unlink ($file)) {
echo "File $file deleted successfully.
";
}else{
echo "File $file Delete failed!
";
}
}
}
if (@rmdir ($dir)) {
echo "Directory $dir deleted successfully.
n ";
}else{
echo "Directory $dir Delete failed!
n ";
}
}
Test program
$dir = "/var/www/test";
Deletedir ($dir);
? > |
http://www.bkjia.com/PHPjc/633086.html www.bkjia.com true http://www.bkjia.com/PHPjc/633086.html techarticle to traverse all the directories in a folder, list all the files inside, PHP itself has a readdir function, but only to read the current directory, according to this function, I ...