Home >Backend Development >PHP Problem >How to delete files in a folder in php
How to delete files in a folder in php: 1. Delete the specified file directly through the unlink() function, the syntax is "unlink($filename)". 2. Use the while statement and the readdir() function to read the contents of the folder in a loop, use is_dir() to determine whether the file exists in the folder, and if it exists, use the unlink() method to delete it until all files in the folder are deleted.
#The operating environment of this article: Windows 7 system, PHP8, Dell G3 computer.
php file deletion uses the unlink() function
First create a file named testFile.txt.
Example
Delete the specified file
$filename = 'file.txt'; fopen($filename,'a+'); if(!unlink($filename)) { echo "文件{$filename}删除失败"; } else { echo "文件{$filename}删除成功"; } ?>
Delete all files in the directory
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 unlink() function description
Function: Delete files.
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.
Return value: true if successful, false if failed.
【Recommended: PHP Video Tutorial】
The above is the detailed content of How to delete files in a folder in php. For more information, please follow other related articles on the PHP Chinese website!