Tutorials, PHP & MySQL

Delete folders from server using PHP

A tutorial to create a function to delete folder and all sub folders from the server.

Start by stating it's a function by issuing the word function followed by a name in this case delete_directory with a parameter this is a variable that contains the name of the directory you want to delete.

function delete_directory($dirname) {

Then an if statement is used to see if the directory is a real directory and if it is then open the directory.

if (is_dir($dirname)){
$dir_handle = opendir($dirname);
}

Then anther if statement is done to see if the directory is valid if it's not then return false is set and the directory won't be deleted.

if (!$dir_handle){
return false;
}

Then a while loop is performed reading the directory contents and adding them at a viable called file to check the files have valid names then delete them from the server using unlink, if the files are invalid then the function is called again with the file name in question.

while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}

Then the directory is closed using closedir then it is removed using readir then returns a success status by using true.

To run the function you need to call it you do so by typing the function name with a parameter inside parenthesis.

delete_directory('foldername');
closedir($dir_handle);
rmdir($dirname);
return true;
}


Here's the full script:<

<?php
function delete_directory($dirname) {
if (is_dir($dirname)){
$dir_handle = opendir($dirname);
}
if (!$dir_handle){
return false;
}

while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}

closedir($dir_handle);
rmdir($dirname);
return true;
}

delete_directory('foldername');?>

That's it run the script to delete any folder from your server using the magic of php!

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.