How do I delete all files and subfolders in a directory?

0

I have a file storage site, and with a while 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 ... Is there a way to execute a < in> PHP to delete all the contents of this folder, but not delete it itself?

Erase by FTP takes a lot .... By PHP I could even create a cron to run in a certain time.

Can anyone help me?

    
asked by anonymous 16.04.2018 / 19:37

1 answer

1

You can list all files within this directory and delete them as follows:

$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 simplified, you can use OS commands to delete the folder, but this solution only works in 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";
    
16.04.2018 / 19:54