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 ?
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 ?
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.
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__);