doutuo1939 2012-11-20 10:34
浏览 62

使用PHP按名称查找重复文件

There are some modules in project which are being renamed or newly created or copied directly. Now I want to delete old directory files. So I want to find all files with their path which are having same name for clean up . (count > 2). That can be css, tpl, php or js files.

i.e.

Main\Games\troy.php
Main\Games\Child Games\troy.php
Main\Games\Sports\troy.php

If search is done on Main directory then search should return all 3 files and their paths. How to find duplicate files by PHP.

That will be useful also for finding duplicate files with same name in your drive like mp3, 3gp files.

  • 写回答

1条回答 默认 最新

  • dousong8187 2012-11-20 10:34
    关注
    function find_duplicate_files() {
        $names = scandir_recursive( 'D:\Main' );
        $files = array();
        foreach( $names as $name ) {
            if( count( $name ) > 1 ) {
                $files[] = $name;
            }
        }
        print_r( $files );
    }
    

    Function scandir_recursive() recursively parses the specified directory tree and creates an associative array whose keys are the file names found in all subdirectories, and whose values are the corresponding paths.

    function scandir_recursive( $dir, &$result = array() ) {
        $dir = rtrim($dir, DIRECTORY_SEPARATOR);
    
        foreach ( scandir($dir) as $node ) {
            if ($node !== '.' and $node !== '..') {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $node)) {
                    scandir_recursive($dir . DIRECTORY_SEPARATOR . $node, $result);
                } else {
                    $result[$node][] = $dir . DIRECTORY_SEPARATOR . $node;
                }
            }
        }
        return $result;
    }
    

    // It will output like

    Array
    (
        [0] => Array
            (
                [0] => D:\Main\Games\troy.php
                [1] => D:\Main\Games\Child Games\troy.php
                [2] => D:\Main\Games\Sports\troy.php 
            )
    
        [1] => Array
            (
                [0] => D:\Main\index.php
                [1] => D:\Main\Games\index.php
            )
    )
    

    From which we can identify which are duplicate files. It is useful when your code base is having large number of files. ( And I have used it a lot for finding duplicate music mp3 files :P )

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源