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

How to delete files in a loop in php

藏色散人
Release: 2023-03-02 06:02:02
Original
2555 people have browsed it

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";
}
}
Copy after login

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();

?>
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template