PHP开发PHP经验分享PHP实战

php获取重复文件,删除重复文件

2020-09-02  本文已影响0人  Renew全栈工程师

上代码

<?php

$files = [];

/**
 * @param $path
 * @param bool $isDir
 * @return Generator|void
 */
function readDirFiles($path, $isDir = false)
{
    $path = rtrim($path, '/*');

    if (!is_readable($path)) return;

    $dh = opendir($path);

    while (($file = readdir($dh)) !== false) {
        if (substr($file, 0, 1) == '.') continue;

        $filePath = $path . DIRECTORY_SEPARATOR . $file;

        if (is_dir($filePath)) {
            $sub = readDirFiles($filePath, $isDir);

            while ($sub->valid()) {
                yield $sub->current();

                $sub->next();
            }

            if ($isDir) yield $filePath;
        } else {
            yield $filePath;
        }
    }

    closedir($dh);
}

foreach (readDirFiles(__DIR__) as $file) {
    $md5 = md5_file($file);

    if (isset($files[$md5])) {
        $to = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $files[$md5]);

        echo "重复文件: {$to}  => " . str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $file) . "\n";
     
        //unlink($file);  // 如果需要删除解除注释即可
    } else {
        $files[$md5] = $file;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读