![]() ![]() However, most the time I just want to perform a delete and move on, without having to think about whether something is a directory or a file. I think the fine control that unlink and rmdir provides still have its place in some cases. Warning: rmdir(dirname): Directory not empty in /var/www/mysite/some_file.php on line 12 Typically using rmdir on a non-empty directory will not work as we intuitively expect, and instead it will result in an error like the below: 'test/' header ( 'Content-type: text/txt' ) if ( simple_delete ( $dir )) rmdir and Directory not empty Since it is possible for a function to call itself, someone has suggested that we do something similar to the below, and I simply tried to improve it by handling errors:ĭefine ( 'BASE_PATH', rtrim ( realpath ( dirname ( _FILE_ )), "/" ). The solution is to create a looping mechanism, which will recursively delete any files and subdirectories within the Before you just copy and paste the solution in this article, you may want to try and come up with your own :-) Luckily, such tasks are not impossibly hard, and they serve as nice learning exercises. In Linux, you can at least use the rm -rf to forcefully remove a directory that is not empty, but in PHP there is no equivalent and it also will not work in Windows. So, we have to come up with our own complex solution. Deleting a directory with content should be handled automatically. Personally, I would prefer a single function to delete both files and directories, as well as non-empty directories. Deleting directories is unnecessarily complicated. Here is an example of a recursive PHP function that deletes every file and folder in a specified directory.The rmdir function of PHP is a bit unintuitive, since it does not work the way most users expect. 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).ĭelete all files and sub-directories in a directory: To delete all files and directories in all sub-directories, we can use recursion.Using the is_file function to check if it is a file and not a parent directory or a sub-directory. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |