使用 ASP 或 PHP 检查文件是否存在于 2 个目录中

问题描述 投票:0回答:5

我正在寻找一种方法来比较两个目录以查看两个目录中是否存在文件。我想要做的是删除其中 1 个目录中的文件(如果两个目录中都存在该文件)。

我可以使用

ASP
PHP

示例:

/devices/1001
/devices/1002
/devices/1003
/devices/1004
/devices/1005

/disabled/1001
/disabled/1002
/disabled/1003

因此,由于

1001, 1002, 1003
存在于/disabled/中,我想将它们从/devices/中删除,只留下
/devices/
中的1004, 1005

php asp.net file-io intersection
5个回答
5
投票

使用

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

作为函数应用,包括检查目录是否有效:

<?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/');

1
投票

使用 PHP 非常简单 - 在本示例中,我们设置两个基本目录和文件名...这可以很容易地成为

foreach()
循环中的数组。然后我们检查这两个目录,看看它是否确实驻留在每个目录中。如果是这样,我们从第一个开始删除。这可以很容易地修改为从第二个删除。

见下图:

<?php 

$filename = 'foo.html';
$dir1 = '/var/www/';
$dir2 = '/var/etc/';
if(file_exists($dir1 . $filename) && file_exists($dir2 . $filename)){
  unlink($dir1 . $filename);
}

1
投票
if ($handle = opendir('/disabled/')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            unlink('/devices/' . $file);            
        }
    }
    closedir($handle);
}

0
投票

在 php 中,用它来检查文件是否存在...它将返回 true 或 false...

file_exists(相对文件路径)


0
投票

对于设备中的每个文件,使用设备中的禁用路径和文件名检查其是否存在于禁用状态。

<%

    Set fso = server.createobject("Scripting.FileSystemObject")

    Set devices   = fso.getfolder(server.mappath("/i/auth/devices/"))
    Set disabledpath  = server.mappath("/i/auth/disabled/")

    For each devicesfile in devices.files
        if directory.fileExists(disablepath & devicesfile.name ) Then 

            Response.Write " YES "
            Response.write directoryfile.name & "<br>"

        Else

            Response.Write " NO "
            Response.write directoryfile.name & "<br>"

        End if 
    Next    

%>
© www.soinside.com 2019 - 2024. All rights reserved.