ItSolutionStuff.com

PHP Remove Directory and Files in Directory Example

By Hardik Savani β€’ May 14, 2024
PHP

This tutorial will give you example of php delete directory and files in directory. you can understand a concept of php remove folder and all files. This post will give you simple example of php remove directory and all files. let’s discuss about how to delete directory with files in php.

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...

Tags: PHP
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

πŸ“Ί Subscribe on YouTube

We Are Recommending You

β˜…

PHP Find URL in Text (String) and Make Link Example

Read Now β†’
β˜…

PHP Dropzone File Upload on Button Click Example

Read Now β†’
β˜…

PHP Multidimensional Array Search By Value Example

Read Now β†’
β˜…

Laravel Move File from One Folder to Another Example

Read Now β†’
β˜…

Laravel Copy File from One Folder to Another Example

Read Now β†’
β˜…

How to Convert String to Date in PHP?

Read Now β†’
β˜…

How to Get Size of Directory in MB Laravel?

Read Now β†’
β˜…

How to Get Folder Path from File Path in PHP?

Read Now β†’
β˜…

How to Get the File Size in PHP?

Read Now β†’
β˜…

How to access PHP variables in JQuery?

Read Now β†’
β˜…

How to Count Number of Files in a Directory in PHP?

Read Now β†’
β˜…

How to Count Files in a Directory using Laravel?

Read Now β†’