我正在寻找一种方法来比较2个目录,看看两个文件是否存在.我想要做的是删除其中一个目录中的文件(如果两个目录中都存在).
我可以使用ASP或PHP.
例:
/devices/1001
/devices/1002
/devices/1003
/devices/1004
/devices/1005
/disabled/1001
/disabled/1002
/disabled/1003
Run Code Online (Sandbox Code Playgroud)
因此,由于1001, 1002, 1003存在/ disabled /,我想从/ devices /中删除它们,只留1004, 1005在/ devices /中.
使用scandir()来获取文件名的每个目录的数组,然后使用array_intersect()发现,存在于任何给定其他参数的第一个数组的元素.
http://au.php.net/manual/en/function.scandir.php
http://au.php.net/manual/en/function.array-intersect.php
<?php
$devices = scandir('/i/auth/devices/');
$disabled = scandir('/i/auth/disabled/');
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink('/i/auth/devices/'.$file);
}
Run Code Online (Sandbox Code Playgroud)
应用为包括检查目录有效的功能:
<?php
function removeDuplicateFiles($removeFrom, $compareTo) {
$removeFromDir = realpath($removeFrom);
if ($removeFromDir === false)
die("Invalid remove from directory: $removeFrom");
$compareToDir = realpath($compareTo);
if ($compareToDir === false)
die("Invalid compare to directory: $compareTo");
$devices = scandir($removeFromDir);
$disabled = scandir($compareToDir);
foreach(array_intersect($devices, $disabled) as $file) {
if ($file == '.' || $file == '..')
continue;
unlink($removeFromDir.DIRECTORY_SEPARATOR.$file);
}
}
removeDuplicateFiles('/i/auth/devices/', '/i/auth/disabled/');
Run Code Online (Sandbox Code Playgroud)