Deleting files and directories in php is actually very simple. There are only two functions, one is unlink and the other is rmdir function. If we want to delete the directory and the files under the directory, we need to use recursion. This article mainly introduces PHP unlink and rmdir deletes the example code of a directory and all files in the directory. Friends who need it can refer to it. I hope it can help everyone.
Function code: Only delete files in the specified directory, without deleting directory folders. The code is as follows:
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 {//开源代码phpfensi.com if( unlink( “$dirName/$item” ) )echo “成功删除文件: $dirName/$item<br />n”; } } } closedir( $handle ); } } }
Assume that you need to delete all files in a directory named "upload" , but there is no need to delete the directory folder, you can complete it through the following code:
<?php delFileUnderDir( ‘upload');?>
php deletes all directories, the code is as follows:
function deltree($pathdir) { echo $pathdir;//调试时用的 if(is_empty_dir($pathdir))//如果是空的 { rmdir($pathdir);//直接删除 } else {//否则读这个目录,除了.和..外 $d=dir($pathdir); while($a=$d->read()) { if(is_file($pathdir.'/'.$a) && ($a!='.') && ($a!='..')){unlink($pathdir.'/'.$a);} //如果是文件就直接删除 if(is_dir($pathdir.'/'.$a) && ($a!='.') && ($a!='..')) {//如果是目录 if(!is_empty_dir($pathdir.'/'.$a))//是否为空 {//如果不是,调用自身,不过是原来的路径+他下级的目录名 deltree($pathdir.'/'.$a); } if(is_empty_dir($pathdir.'/'.$a)) {//如果是空就直接删除 rmdir($pathdir.'/'.$a); } } } $d->close(); echo "必须先删除目录下的所有文件";//我调试时用的 } } function is_empty_dir($pathdir) { //判断目录是否为空 $d=opendir($pathdir); $i=0; while($a=readdir($d)) { $i++; } closedir($d); if($i>2){return false;} else return true; }
PHP deletes the directory and all files under the directory, the code is as follows:
<?php //循环删除目录和文件函数 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”; } } //假设需要删除一个名叫”upload”的同级目录即此目录下的所有文件,你可以通过以下代码完成: delDirAndFile( ‘upload'); ?>
Related recommendations:
PHP Deletion of files and folder operations Use of the two functions unlink() and rmdir()
Introduction to the usage of unlink(), mkdir(), rmdir(), etc. in php
The above is the detailed content of PHP's unlink and rmdir methods to delete a directory and all files in the directory. For more information, please follow other related articles on the PHP Chinese website!