Delete folders from server using PHP

David Carr

Tutorials PHP & MySQL

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!

Copyright © 2006 - 2024 DC Blog - All rights reserved.