美文网首页PHP开发PHP经验分享PHP实战
php获取重复文件,删除重复文件

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

作者: Renew全栈工程师 | 来源:发表于2020-09-02 13:24 被阅读0次

    上代码

    <?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;
        }
    }
    

    相关文章

      网友评论

        本文标题:php获取重复文件,删除重复文件

        本文链接:https://www.haomeiwen.com/subject/mktwsktx.html