Delete folder with CHMOD777 permission

Asked

Viewed 186 times

0

I create a folder with PHP like this

mkdir('/public_html/buscauiva/public_html/'.$_POST['Nome'].'', 0777);

To delete I am using the rmdir() of PHP

dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

if(rmdir($dir)) 
{
echo 'Pasta deletada com sucesso.';
}
else 
{
echo 'A pasta não pode ser deletada.';
}

But PHP cannot delete the folder by returning the error: Folder cannot be deleted.

How do I delete the folder with php ( contains files inside)?

  • when creating the folder you don’t need the full path (/var/www/casamentowagnerecamila.com.br). You cannot remove this at the time of deleting as well?

  • yes I did it, but it returns error The folder cannot be deleted

  • in the else, prints error_get_last(); to see what the real mistake is and put in the question, it might help.

  • did not return any error with error_get_last();

2 answers

3


To delete a folder, you first need to delete the files inside it. You can try this way:

$dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

// Se a pasta não existir
if (!file_exists($dir)) {
    echo "Pasta não existe";
}

// Se não for uma pasta, exclui o arquivo
if (!is_dir($dir)) {
    unlink($dir);
}

// Verifica os arquivos dentro da pasta
foreach (scandir($dir) as $item) {
    unlink($item);
}

// Por fim, apaga a pasta
rmdir($dir);

More simply, you can use OS commands to delete the folder, but this solution only works on LINUX (I think)

// chama o comando do SO
system('rm -rf ' . escapeshellarg($dir), $retorno);
// esse comando linux retorna 0 quando sucesso
if( $retorno == 0) echo "Excluido com sucesso";

1

I went to check on PHP manual and saw that to delete the folder, "the directory has to be empty and the relevant permissions authorize this operation".

In the manual itself there is an example of how to proceed; you need clean up the directory and then delete it, you would use so:

public static function MeuMetodo()
{
  // ...      
  dir='/var/www/casamentowagnerecamila.com.br/public_html/buscauiva/public_html/'.$row['nome'].'';

  if(DelTree($dir)) 
  {
    echo 'Pasta deletada com sucesso.';
  }
  else 
  {
    echo 'A pasta não pode ser deletada.';
  }
}

public static function DelTree($dir) { 
  files = array_diff(scandir($dir), array('.','..')); 
  foreach ($files as $file) { 
    (is_dir("$dir/$file")) ? delTree("$dir/$file") : unlink("$dir/$file"); 
  } 
  return rmdir($dir); 
} 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.