Search code examples
phpfunctioncurly-braces

Why this function is not working? PHP


This is the original function and this works perfectly...

    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;
  }

I tried to do a version with curly braces and different names but it is not working and I'm not sure what the problem is

    function borrar_directorio ($carpeta) {

  if (is_dir($carpeta)) {

    $abrir_directorio = opendir($carpeta);

    if (!$abrir_directorio) {

      return false;
    }
  }

  while ($archivo = readdir($abrir_directorio)) {

      if ($archivo != "." && $archivo != "..") {

        if (!is_dir($carpeta."/".$archivo)) {
          unlink($carpeta."/".$achivo);

        } else {

          borrar_directorio($carpeta.'/'.$archivo);
        }
      }
    }

  closedir($abrir_directorio);
  rmdir($carpeta);
  return true;
}

What I'm missing? I hope you can help me, thanks in advance


Solution

  • One possible problem in how you have written it is that if the folder does not exist or can not be opened due to permission restrictions or filesystem errors, the while loop will still run.

    Here's how the original script should be written using curly-braces

      if(is_dir($carpeta))
      {
        $abrir_directorio = opendir($carpeta);
      }
      if(!$abrir_directorio)
      {
        return false;
      }
    
      while($archivo = readdir($abrir_directorio))
      { ...