This article will provide some of the most important example how to delete directory with files in php. step by step explain php remove dir and all contents. you can see how to delete all files and folder in a folder php. This tutorial will give you simple example of php delete directory and files in directory.
Sometime, we need to delete all files and directory in a directory using php code. so in this post i will help you how to remove folder with all contents inside that folder.
Let's see both example that will helps you.
Example 1:
Code:
<?php
$folderName = 'images';
removeFolder($folderName);
function removeFolder($folderName) {
if (is_dir($folderName))
$folderHandle = opendir($folderName);
if (!$folderHandle)
return false;
while($file = readdir($folderHandle)) {
if ($file != "." && $file != "..") {
if (!is_dir($folderName."/".$file))
unlink($folderName."/".$file);
else
removeFolder($folderName.'/'.$file);
}
}
closedir($folderHandle);
rmdir($folderName);
return true;
}
?>
Example 2:
Code:
<?php
$folderName = 'images2';
removeFiles($folderName);
function removeFiles($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK );
foreach( $files as $file ){
removeFiles( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
}
?>
I hope it can help you...
Do you like below Tutorials ?
- How to Display Data in Angular 10?
- Angular 10 Routing Module Example Tutorial
- Angular 10 CRUD Operations with Web API Example
- Laravel 8 CRUD Operation Step By Step Tutorial
- Solved - Target class [ProductController] does not exist in Laravel 8
- Step by Step Form Validation in Laravel 8 Example
- Laravel 8 Image Upload with Preview Example
- Laravel 8 Multiple Images Upload with Preview Example