Search code examples
phphtmlrecursiondirectoryunlink

Search for txt files with a certain name and then delete them using PHP?


Using the unlink function in php is it possible to search a directory with multiple folders for txt files with a certain name. In my case Newsfeed.txt

Where should I start with this ?


Solution

  • Great answer maxhb. Here's something a little more manual.

    <?php
    
    function unlink_newsfeed($checkThisPath) {
        $undesiredFileName = 'Newsfeed.txt';
    
        foreach(scandir($checkThisPath) as $path) {
            if (preg_match('/^(\.|\.\.)$/', $path)) {
                continue;
            }
    
            if (is_dir("$checkThisPath/$path")) {
                unlink_newsfeed("$checkThisPath/$path");
            } else if (preg_match( "/$undesiredFileName$/", $path)) {
                unlink("$checkThisPath/$path");
            }
        }
    }
    
    unlink_newsfeed(__DIR__);