IT박스

PHP를 사용하여 디렉토리가 비어 있는지 어떻게 확인할 수 있습니까?

itboxs 2020. 10. 28. 07:54
반응형

PHP를 사용하여 디렉토리가 비어 있는지 어떻게 확인할 수 있습니까?


다음 스크립트를 사용하여 디렉토리를 읽고 있습니다. 디렉토리에 파일이 없으면 비어 있어야합니다. 문제는 내부에 ARE 파일이 있고 그 반대의 경우에도 디렉토리가 비어 있다고 계속 말하는 것입니다.

<?php
$pid    =       $_GET["prodref"];
$dir    =       '/assets/'.$pid.'/v';
$q     =        (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

    if ($q=="Empty")
        echo "the folder is empty"; 
    else
        echo "the folder is NOT empty";
?>

scandirglob은 unix 숨겨진 파일을 볼 수 없기 때문에 glob 대신 필요한 것 같습니다 .

<?php
$pid = basename($_GET["prodref"]); //let's sanitize it a bit
$dir = "/assets/$pid/v";

if (is_dir_empty($dir)) {
  echo "the folder is empty"; 
}else{
  echo "the folder is NOT empty";
}

function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  return (count(scandir($dir)) == 2);
}
?>

이 코드는 효율성의 정상이 아닙니다. 디렉토리가 비어 있는지 여부 만 알기 위해 모든 파일을 읽을 필요가 없기 때문입니다. 따라서 더 나은 버전은

function dir_is_empty($dir) {
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      closedir($handle);
      return FALSE;
    }
  }
  closedir($handle);
  return TRUE;
}

그런데 부울을 대체 하기 위해 단어사용하지 마십시오 . 후자의 목적은 무언가가 비어 있는지 여부를 알려주는 것입니다.

a === b

표현식은 이미 Empty또는 Non Empty프로그래밍 언어 측면에서 FALSE또는 TRUE각각 반환 하므로 IF()중간 값없이 같은 제어 구조에서 바로 결과를 사용할 수 있습니다.


FilesystemIterator를 사용하는 것이 가장 빠르고 쉬운 방법 이라고 생각합니다 .

// PHP 5 >= 5.3.0
$iterator = new \FilesystemIterator($dir);
$isDirEmpty = !$iterator->valid();

또는 인스턴스화시 클래스 멤버 액세스 사용 :

// PHP 5 >= 5.4.0
$isDirEmpty = !(new \FilesystemIterator($dir))->valid();

이는 new FilesystemIterator가 처음에 폴더의 첫 번째 파일을 가리 키기 때문에 작동 합니다. 폴더에 파일이 없으면 valid()을 반환 false합니다. ( 여기에서 문서를 참조 하십시오 .)

abdulmanov.ilmir가 지적했듯이, 선택적으로를 사용하기 전에 디렉토리가 존재하는지 확인하십시오 . FileSystemIterator그렇지 않으면 UnexpectedValueException.


빠른 해결책을 찾았습니다

<?php
  $dir = 'directory'; // dir path assign here
  echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>

사용하다

if ($q == "Empty")

대신에

if ($q="Empty")

이 시도:

<?php
$dirPath = "Add your path here";

$destdir = $dirPath;

$handle = opendir($destdir);
$c = 0;
while ($file = readdir($handle)&& $c<3) {
    $c++;
}

if ($c>2) {
    print "Not empty";
} else {
    print "Empty";
} 

?>

아마도 if문장 의 할당 연산자 때문일 것입니다 .

변화:

if ($q="Empty")

에:

if ($q=="Empty")

이것은 매우 오래된 실이지만 10 센트를 줄 것이라고 생각했습니다. 다른 솔루션은 저에게 효과적이지 않았습니다.

내 해결책은 다음과 같습니다.

function is_dir_empty($dir) {
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if($fileInfo->isDot()) continue;
        return false;
    }
    return true;
}

짧고 달다. 매력처럼 작동합니다.


를 사용하여 객체 지향 접근 방식 RecursiveDirectoryIterator으로부터 표준 PHP 라이브러리 (SPL) .

<?php

namespace My\Folder;

use RecursiveDirectoryIterator;

class FileHelper
{
    /**
     * @param string $dir
     * @return bool
     */
    public static function isEmpty($dir)
    {
        $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
        return iterator_count($di) === 0;
    }
}

필요할 FileHelper때마다 인스턴스를 만들 필요가 없으며 다음과 같이 필요할 때마다이 정적 메서드에 액세스 할 수 있습니다.

FileHelper::isEmpty($dir);

FileHelper클래스는 등, 복사 삭제, 이름 변경을위한 다른 유용한 방법으로 확장 할 수 있습니다

메서드 내에서 디렉터리의 유효성을 확인할 필요가 없습니다. 유효하지 않은 경우 생성자가 해당 부분을 충분히 포함 RecursiveDirectoryIterator하는를 던지기 때문 UnexpectedValueException입니다.


@ 상식

엄격한 비교를 사용하면 성능이 더 좋은 예가 될 수 있다고 생각합니다.

function is_dir_empty($dir) {
  if (!is_readable($dir)) return null; 
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
      closedir($handle); // <-- always clean up! Close the directory stream
      return false;
    }
  }
  closedir($handle); // <-- always clean up! Close the directory stream
  return true;
}

다음과 같이 코드를 수정하십시오.

<?php
    $pid = $_GET["prodref"];
    $dir = '/assets/'.$pid.'/v';
    $q = count(glob("$dir/*")) == 0;

    if ($q) {
        echo "the folder is empty"; 
    } else {
        echo "the folder is NOT empty";
    }
?>

내 Wordpress CSV 2 POST 플러그인에서이 방법을 사용합니다.

    public function does_folder_contain_file_type( $path, $extension ){
        $all_files  = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

        $html_files = new RegexIterator( $all_files, '/\.'.$extension.'/' );  

        foreach( $html_files as $file) {
            return true;// a file with $extension was found
        }   

    return false;// no files with our extension found
}

특정 확장자로 작동하지만 "new RegexIterator ("줄을 제거하여 필요에 맞게 쉽게 변경할 수 있습니다. $ all_files 개수를 계산합니다.

    public function does_folder_contain_file_type( $path, $extension ){
        $all_files  = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $path ) );

        return count( $all_files );
    }

최근에 비슷한 문제가 있었지만 가장 높은 찬성 응답이 실제로 효과가 없었기 때문에 비슷한 해결책을 찾아야했습니다. 그리고 이것은 또한 문제를 해결하는 가장 효율적인 방법이 아닐 수도 있습니다.

이렇게 함수를 만들었습니다.

function is_empty_dir($dir)
   {
       if (is_dir($dir))
       {
            $objects = scandir($dir);
            foreach ($objects as $object)
            {
                if ($object != "." && $object != "..")
                {
                    if (filetype($dir."/".$object) == "dir")
                    {
                         return false;
                    } else { 
                        return false;
                    }
                }
            }
            reset($objects);
            return true;
       }

이렇게 빈 드라이 스토리를 확인하는데 사용했습니다.

if(is_empty_dir($path)){
            rmdir($path);
        }

이것을 사용할 수 있습니다 :

function isEmptyDir($dir)
{
    return (($files = @scandir($dir)) && count($files) <= 2);
}

The first question is when is a directory empty? In a directory there are 2 files the '.' and '..'.
Next to that on a Mac there maybe the file '.DS_Store'. This file is created when some kind of content is added to the directory. If these 3 files are in the directory you may say the directory is empty. So to test if a directory is empty (without testing if $dir is a directory):

function isDirEmpty( $dir ) {
  $count = 0;
  foreach (new DirectoryIterator( $dir ) as $fileInfo) {
     if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
        continue;
     }
     $count++;
  }
  return ($count === 0);
}

@Your Common Sense,@Enyby

Some improvement of your code:

function dir_is_empty($dir) {
    $handle = opendir($dir);
    $result = true;
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $result = false;
            break 2;
        }
    }
    closedir($handle);
    return $result;
}

I use a variable for storing the result and set it to true.
If the directory is empty the only files that are returned are . and .. (on a linux server, you could extend the condition for mac if you need to) and therefore the condition is true.
Then the value of result is set to false and break 2 exit the if and the while loop so the next statement executed is closedir.
Therefore the while loop will only have 3 circles before it will end regardless if the directory is empty or not.

참고URL : https://stackoverflow.com/questions/7497733/how-can-i-use-php-to-check-if-a-directory-is-empty

반응형