Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP script to remove dot files from Linux directory

Tags:

file

php

erase

I have been working on a project that involves a step, during which the script needs to automatically remove a certain directory in Linux ( and all its contents ).

I am currently using the following code to do that:

# Perform a recursive removal of the obsolete folder
$dir_to_erase = $_SESSION['path'];
function removeDirectory($dir_to_erase) {
    $files = glob($dir_to_erase . '/*');
    foreach ($files as $file) {
        is_dir($file) ? removeDirectory($file) : unlink($file);
    }
    rmdir($dir_to_erase);
    return; 
}

Where $_SESSION['path'] is the folder to erase. Been working like a charm, but I recently had to add a .htaccess file to the folder, and I noticed the script stopped working correctly ( it keeps removing the rest of the files fine, but not the .htaccess files ).

Can anyone point me as to what I should add to the code include the hidden dot files in the removal process?

like image 977
Peter Avatar asked Apr 21 '26 04:04

Peter


1 Answers

simply, you can rely on DirectoryIterator

The DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.

function removeDirectory($dir_to_erase) {
    $files = new DirectoryIterator($dir_to_erase);
    foreach ($files as $file) {
        // check if not . or ..
        if (!$file->isDot()) {
            $file->isDir() ? removeDirectory($file->getPathname()) : unlink($file->getPathname());
        }
    }
    rmdir($dir_to_erase);
    return;
}

there are lot of features there you may make use of them, as check the owner which is pretty useful to make sure not to remove critical file.

like image 113
hassan Avatar answered Apr 22 '26 19:04

hassan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!