How to delete all files and subfolders from a directory?

Asked

Viewed 766 times

1

I have a file storage site, and with time it moves inactive files to a folder: www.site.com/files/_deleted/, when it moves the files it creates a subfolder for each of them... It has how I run a code PHP to delete all contents of this folder, but not erase her herself?

Blot out FTP it takes long.... By PHP I could even create a cron to run at a certain time.

Can someone help me ?

1 answer

2


You can list all files within this directory and delete them that way:

$arquivos = scandir(www.site.com/files/_deleted/);

foreach ($arquivos as $arquivo){

    // Verifica se é uma subpasta e apaga os arquivos dentro
    foreach (scandir($arquivo) as $item) {
        unlink($item);
    }

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

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

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

$dir = 'www.site.com/files/_deleted/*';
// 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";
  • In the case www.site.com/files/_Deleted/ I can only put /files/_Deleted/ by it hosted on the same server...

  • Good. Test there and any doubt tells me :)

  • It didn’t work.... error 500

  • However the simplified form worked...but it also deletes the folder.. I wanted it to delete only what is inside it...

  • Hmm, to not delete the folder itself, put a * at the end of the path. I will edit the answer.

  • Thank you very much!

Show 1 more comment

Browser other questions tagged

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