To delete a file in php, you only need to use the unlink function to delete the file. If you want to delete all the files in the directory, You need to delete them using recursive operations.
Please refer to the tutorial on creating a PHP file. We created a file named testfile.txt.
The Code is as follows: |
Copy code |
$ MyFile = "testFile.txt "; $ Fh = fopen ($ myFile, 'w') or die ("can't open file "); Fclose ($ fh ); Determine whether the object has been deleted. $ MyFile = "testFile.txt "; Unlink ($ myFile ); |
Example
The Code is as follows: |
Copy code |
$ Filename = 'file.txt '; Fopen ($ filename, 'a + '); If (! Unlink ($ filename )) { Echo "failed to delete the file {$ filename "; } Else { Echo "the file {$ filename} is successfully deleted "; } ?> |
Delete all files in the directory
The Code is as follows: |
Copy code |
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 "successfully deleted the file: $ dirName/$ item <br/> n "; } } } Closedir ($ handle ); } } |