【问题标题】:How to move repeated files from folder to another in php?如何在php中将重复的文件从文件夹移动到另一个?
【发布时间】:2015-02-05 23:30:26
【问题描述】:

我想扫描我的whatsapp图像文件夹并将所有重复的图像移动到名为recycle bin的文件夹中以便稍后删除它们,这是我的代码:

<?php

$dir    = 'C:\wamp\www\whatsapp';
$files = scandir($dir);

$x = 0;

foreach($files as $f1)
{

    $crc1 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f1))));

    unset($files[$x]);

    $j = 0;

    foreach($files as $f2)
    {

        $crc2 = strtoupper(dechex(crc32(file_get_contents("whatsapp/".$f2))));

        if($crc1 == $crc2){

            rename("whatsapp/".$f2, "recycle bin/".$f2);

            unset($files[$j]);
        }

        $j++;
    }

    $x++;
}

exit('Done');

是否可以信任此代码仅移动重复的图像而不会出现任何错误?

【问题讨论】:

  • 效率很低。只需对每个文件进行一次哈希处理,将哈希值放入数组中,如果下一个文件的哈希值已经在数组中,您就知道可以移动它……而不是再次对每个文件进行哈希处理以查看是否存在欺骗。
  • 这属于codereview.stackexchange.com而不是SO。
  • @rjdown 你能写一个例子吗?

标签: php file-rename scandir


【解决方案1】:

我已经为您的案例编写了一个小脚本(但我还没有测试过):

<?php

$fileHashes = [];

foreach(scandir('C:\wamp\www\whatsapp') as $file){
    $fileHashes["whatsapp/".$file] = sha1(file_get_contents("whatsapp/".$file));
}

$doubles = array_diff_key($fileHashes, array_unique($fileHashes))
foreach($doubles as $file=>$hash){
    unlink($file);
}

exit('Done');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多