In PHP if you want to delete the file or directory then keep one thing in mind that you cannot delete the file or directory directly there is a condition on that i.e. there are some security issues are there so the best way to do this is you first have to delete the data present in the file or the sub files or directories present in it . Then only you are able to delete the directory . And after deleting the sub directories or files use the rmdir function to delete the main directory.
PHP function to delete all files: In the following code, first passing the path of directory which need to delete. It checks whether the file or directory which need to delete is actually present/exist or not. If it does exist then it will open the file check whether there is something in that file or not. If not then delete the directory using rmdir directory. But if any other files are present in the directory if then it will delete the files using unlink function except the . and .. files which means the system files. After deleting all the stuff just use the rmdir function to delete the directory completely.
- Before Removing the files:
- After Removing the files:
- In this above example, deleting all files from a folder called “temp”.
- List the files in this directory by using PHP glob function. The glob function basically “finds pathnames that match a certain pattern”. In this case, use a wildcard * (asterix) to select everything that is in the “temp” folder.
- The glob function returns an array of file names that are in the specified folder.
- Loop through this array.
- Using the is_file function to check if it is a file and not a parent directory or a sub-directory.
- Finally, use the unlink function, which deletes the file (if PHP has valid permissions – if not, an E_WARNING error will be thrown and the function will return a boolean FALSE value).
- Before removing the directory:
- After removing the directory: The directory is completely deleted.
Delete all files and sub-directories in a directory: To delete all files and directories in all sub-directories, we can use recursion. Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.
The function checks if the $str variable represents a path to a file then it deletes the file using the function unlink. However, if $str represents a directory, then it gets a list of all files in said directory before deleting each one. Finally, it removes the sub-directory itself by using PHP rmdir function.