开发者

How to detect files with same name in various directories?

开发者 https://www.devze.com 2023-03-09 14:24 出处:网络
Suppose there are 2 directories on my server: /xyz/public_html/a/ /xyz/public_html/b/ And both of them consist of many files. How do i de开发者_开发知识库tect the files that are common to both the

Suppose there are 2 directories on my server:

/xyz/public_html/a/
/xyz/public_html/b/

And both of them consist of many files. How do i de开发者_开发知识库tect the files that are common to both the folders in terms of their name and file_extension. This program is to be implemented in PHP. Any suggestions?


Using FileSystemIterator, you might do something like this...

<?

$it = new FilesystemIterator('/xyz/public_html/a/');

$commonFiles = array();

foreach ($it as $file) {
    if ($file->isDot() || $file->isDir()) continue;

    if (file_exists('/xyz/public_html/b/' . $file->getFilename())) {
        $commonFiles[] = $file->getFilename();
    }
}

Basically, you have to loop through all the files in one directory, and see if any identically-named files exist in the other directory. Remember that the file name includes the extension.


If it’s just two directories, you could use an algorithm similar to the merge algorithm of merge sort where you have two lists of already sorted items and walk them simultaneously while comparing the current items:

$iter1 = new FilesystemIterator('/xyz/public_html/a/');
$iter2 = new FilesystemIterator('/xyz/public_html/b/');
while ($iter1->valid() && $iter2->valid()) {
    $diff = strcmp($iter1->current()->getFilename(), $iter2->current()->getFilename());
    if ($diff === 0) {
        // duplicate found
    } else if ($diff < 0) {
        $iter1->next();
    } else {
        $iter2->next();
    }
}

Another solution would be to use the uniqueness of array keys so that you put each directory item into an array as key and then check for each item of the other directory if such a key exists:

$arr = array();
$iter1 = new FilesystemIterator('/xyz/public_html/a/');
foreach ($iter1 as $item) {
    $arr[$item->getFilename()] = true;
}
$iter2 = new FilesystemIterator('/xyz/public_html/a/');
foreach ($iter2 as $item) {
    if (array_key_exists($item->getFilename(), $arr)) {
        // duplicate found
    }
}


If you just want to find out which are in common, you can easily use scandir twice and find what's in common, for example:

//Remove first two elements, which will be the constant . and .. Not a very sexy solution
$filesInA = array_shift(array_shift(scandir('/xyz/publichtml/a/')));
$filesInB = array_shift(array_shift(scandir('/xyz/publichtml/b/')));

$filesInCommon = array_intersect($filesInA, $filesInB);
0

精彩评论

暂无评论...
验证码 换一张
取 消