PHP Tutorial
Home
PHP Install Xampp
PHP Syntax & Comments
PHP Variables
PHP Constants
PHP Data Types
PHP Echo & Print
PHP Strings
PHP If...Else...Elseif
PHP Ternary Operator
PHP Loops
PHP Functions
PHP Arrays
PHP GET & POST
PHP Advanced
PHP Date and Time
PHP Include and Require
PHP File Upload
PHP Sessions
PHP Cookies
PHP Send Email
PHP JSON Parsing
PHP MySQL Database
PHP MySQL Introduction
PHP Connect to MySQL
PHP MySQL Create DB
PHP MySQL Create Table
PHP MySQL Insert Data
PHP MySQL Select Data
PHP MySQL Delete Data
PHP MySQL Update Data
PHP MySQL Where
In PHP if you want to delete a directory there is security in deleting the directory with files in it. So you need to delete all the files in the folder before you can delete the directory. Below is a small function that will appear in the directory if any files in it will be deleted and the directory will be deleted. This operation will also delete the directions below. You can extend this function by adding additional logic to see that the $ directory name name is not a guide to simply delete a file.
Sometimes, we need to delete all files and directions in the directory using php code. so in this post I will help you how to delete a folder and all the content within that folder.
Example 1:
<?php function delete_folder($dir_name) { if (is_dir($dir_name)) $dir_handle = opendir($dir_name); if (!$dir_handle) return false; while($file_name = readdir($dir_handle)) { if ($file_name != "." && $file_name != "..") { if (!is_dir($dir_name."/".$file_name )) unlink($dir_name."/".$file_name ); else delete_folder($dir_name.'/'.$file_name ); } } closedir($dir_handle); rmdir($dir_name); return true; } ?>
Example 2:
<?php $folder_name = 'photos'; removeFiles($folder_name ); function removeFiles($target_file) { if(is_dir($target_file)){ $files = glob( $target_file . '*', GLOB_MARK ); foreach( $files as $file ){ removeFiles( $file ); } rmdir( $target_file); } elseif(is_file($target_file)) { unlink( $target_file); } } ?>