Home  >  Article  >  Backend Development  >  How to delete files in a loop in php

How to delete files in a loop in php

藏色散人
藏色散人Original
2020-07-06 10:25:182457browse

php method to delete files in a loop: first create a PHP code sample file; then define a delDirAndFile method; then implement the logical function of loop deletion through while if and other statements in the method body; finally save and run the file That’s it.

How to delete files in a loop in php

php loop deletes files, directories and files

Delete files and directories:

//循环删除目录和文件函数
function delDirAndFile( $dirName )
{
if ( $handle = opendir( "$dirName" ) ) {
   while ( false !== ( $item = readdir( $handle ) ) ) {
   if ( $item != "." && $item != ".." ) {
   if ( is_dir( "$dirName/$item" ) ) {
   delDirAndFile( "$dirName/$item" );
   } else {
   if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item<br />\n";
   }
   }
   }
   closedir( $handle );
   if( rmdir( $dirName ) )echo "成功删除目录: $dirName<br />\n";
}
}

Delete Files are not deleted from the directory:

class shanchu {
//循环目录下的所有文件
function delFileUnderDir( $dirName="../Smarty/templates/templates_c" )
{
if ( $handle = opendir( "$dirName" ) ) {
   while ( false !== ( $item = readdir( $handle ) ) ) {
   if ( $item != "." && $item != ".." ) {
   if ( is_dir( "$dirName/$item" ) ) {
         delFileUnderDir( "$dirName/$item" );
   } else {
   if( unlink( "$dirName/$item" ) )echo "成功删除文件: $dirName/$item<br />\n";
   }
   }
   }
   closedir( $handle );
}
}
}
?>
<?php
$user = new shanchu();
$user->delFileUnderDir();

?>

For a lot of related knowledge, please visit PHP Chinese website!

The above is the detailed content of How to delete files in a loop in php. 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