php unlink method to delete a directory: first create a PHP sample file; then delete the directory and files through loop traversal and unlink function.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
The unlink() function deletes files.
If successful, return true, otherwise return false.
Syntax
unlink(filename,context)
Parameters
filename required. Specifies the files to be deleted.
context Optional. Specifies the environment for a file handle. Context is a set of options that modify the behavior of the stream.
PHP deletes the directory and all files in 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'); ?>
[Recommended learning: "PHP Video Tutorial 》】
The above is the detailed content of How to delete directory in php unlink. For more information, please follow other related articles on the PHP Chinese website!