0

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 ?

maxhb
  • 8,554
  • 9
  • 29
  • 53
Tom Buxton
  • 35
  • 1
  • 5
  • Get all file name inside a directory:- http://stackoverflow.com/questions/2922954/getting-the-names-of-all-files-in-a-directory-with-php. now with foreach check the filename and delete them. – Alive to die - Anant Feb 02 '16 at 19:25

2 Answers2

1

You could use the recursive directory iterators of the php standard library (SPL).

function deleteFileRecursive($path, $filename) {
  $dirIterator = new RecursiveDirectoryIterator($path);
  $iterator = new RecursiveIteratorIterator(
    $dirIterator,
    RecursiveIteratorIterator::SELF_FIRST
  );

  foreach ($iterator as $file) {
    if(basename($file) == $filename) unlink($file);
  }
}

deleteFileRecursive('/path/to/delete/from/', 'Newsfeed.txt');

This will allow you to delete all files with name Newsfeed.txt from the given folder and all subfolders.

maxhb
  • 8,554
  • 9
  • 29
  • 53
  • Okay, I should have explained that php is very new to me. So The first part searches a set directory and puts all the results in $dirItnerator. I get that bit. – Tom Buxton Feb 02 '16 at 19:46
  • But I don't understand how to search the $dirIterator for files named Newsfeed.txt? and unlink all of them ?. Sorry – Tom Buxton Feb 02 '16 at 19:47
  • Edited example to meet your requirements. – maxhb Feb 02 '16 at 20:08
1

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__);
Iwnnay
  • 1,933
  • 17
  • 18