How can I delete the contents of a folder with PHP? – Education Career Blog

I can’t seem to get this function to delete all my files and folders in a specific directory can someone help me fix this problem?

Here is my code.

$apps = 9;
$dirname = './members/' . $apps . '/';
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;
}

,

Your function looks fine.

I guess you are not calling it correctly. One way to call it is:

$apps = 9;
$dirname = './members/' . $apps . '/';
delete_directory($dirname);

function delete_directory($dirname) {
.....

,

function EmptyDir($dir) 
{
    $handle=opendir($dir);
    while (($file = readdir($handle))!==false) {
        unlink($dir.'/'.$file);
    }
    closedir($handle);
}

EmptyDir('yourdir'); 

,

Should the initial directory have a trailing slash?

$dirname = './members/' . $apps;

Leave a Comment