디렉토리가 비어 있는지 확인하기 위해 PHP를 사용하는 방법은 무엇입니까?
다음 스크립트를 사용하여 디렉토리를 읽고 있습니다.디렉토리에 파일이 없는 경우는, 「empty」라고 표시됩니다.문제는 내부에 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";
?>
필요한 것 요.scandirfiles를 수 에 glob은 unix hidden files를 볼 수 없습니다.
<?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()
파일 시스템을 사용하여반복기는 가장 빠르고 쉬운 방법입니다.
// PHP 5 >= 5.3.0
$iterator = new \FilesystemIterator($dir);
$isDirEmpty = !$iterator->valid();
인스턴스화 시 클래스 구성원 액세스 사용:
// PHP 5 >= 5.4.0
$isDirEmpty = !(new \FilesystemIterator($dir))->valid();
은, 새로운 「 」가 있기 때문에 합니다.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")
Standard PHP Library(SPL; 표준 PHP 라이브러리)의 를 사용하는 객체 지향 접근법.
<?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클래스를 복사, 삭제, 이름 변경 등을 위한 다른 유용한 방법으로 확장할 수 있습니다.
할 필요는 .디렉토리가 , 디렉토리 가 됩니다.디렉토리가 무효인 경우, 이 디렉토리의 생성자가RecursiveDirectoryIteratorUnexpectedValueException그 부분은 충분히 커버할 수 있습니다.
이것은 아주 오래된 실이지만, 나는 10센트를 바쳐야겠다고 생각했다.다른 솔루션은 나에게 효과가 없었다.
저의 솔루션은 다음과 같습니다.
function is_dir_empty($dir) {
foreach (new DirectoryIterator($dir) as $fileInfo) {
if($fileInfo->isDot()) continue;
return false;
}
return true;
}
짧고 달콤하다.마법처럼 작동한다.
사용:
if(is_readable($dir)&&count(scandir($dir))==2) ... //then the dir is 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")
@ 당신의 상식
엄격한 비교를 통해 성능을 높일 수 있다고 생각합니다.
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;
}
기능.count대용량 어레이에서는 사용량이 느릴 수 있습니다. isset어느 때보다 빠르다
PHP > = 5.4.0에서 올바르게 작동합니다(여기의 Changelog 참조).
function dir_is_empty($path){ //$path is realpath or relative path
$d = scandir($path, SCANDIR_SORT_NONE ); // get dir, without sorting improve performace (see Comment below).
if ($d){
// avoid "count($d)", much faster on big array.
// Index 2 means that there is a third element after ".." and "."
return !isset($d[2]);
}
return false; // or throw an error
}
그렇지 않으면 @Your Common Sense 솔루션을 사용하여 RAM에 파일 목록을 로드하지 않도록 하는 것이 좋습니다.
감사합니다.또한 @soger에게 투표하여 이 답변을 개선합니다.SCANDIR_SORT_NONE선택.
코드를 다음과 같이 수정합니다.
<?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";
}
?>
빈 디렉토리에도 2개의 파일이 포함되어 있습니다..그리고...하나는 현재 디렉토리에 대한 링크이고 다른 하나는 부모 디렉토리에 대한 링크입니다.따라서 다음과 같은 코드를 사용할 수 있습니다.
$files = scandir("path to directory/");
if(count($files) == 2) {
//do something if 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
}
특정 내선번호로 동작하지만 '새로운 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);
}
첫 번째 질문은 디렉토리가 비어 있는 경우입니다.디렉토리에는, 「.」와 「..」의 2개의 파일이 있습니다.
Mac의 그 옆에 '라는 파일이 있을 수 있습니다.DS_Store'를 선택합니다.이 파일은, 디렉토리에 컨텐츠가 추가되었을 때에 작성됩니다.이러한 3개의 파일이 디렉토리에 있는 경우는, 디렉토리가 비어 있다고 말할 수 있습니다.디렉토리가 비어 있는지 테스트하려면($dir가 디렉토리인지 테스트하지 않고) 다음 절차를 수행합니다.
function isDirEmpty( $dir ) {
$count = 0;
foreach (new DirectoryIterator( $dir ) as $fileInfo) {
if ( $fileInfo->isDot() || $fileInfo->getBasename() == '.DS_Store' ) {
continue;
}
$count++;
}
return ($count === 0);
}
@상식, @Enyby
코드 개선 사항:
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;
}
변수를 사용하여 결과를 저장하고 true로 설정합니다.
디렉토리가 비어 있는 경우 반환되는 파일은 와 뿐입니다.(Linux 서버에서는 필요에 따라 mac 조건을 확장할 수 있습니다).따라서 조건이 True입니다.
다음으로 결과값이 false로 설정되고 break 2는 if 및 while 루프를 종료하므로 다음 실행문이 closedir가 됩니다.
따라서 while loop은 디렉토리가 비어 있는지 여부에 관계없이 종료되기 전에 3개의 원밖에 없습니다.
$is_folder_empty = function(string $folder) : bool {
if (!is_dir($folder))
return TRUE;
// This wont work on non linux OS.
return is_null(shell_exec("ls {$folder}"));
};
$is_folder_empty2 = function(string $folder) : bool {
if (!is_dir($folder))
return TRUE;
// Empty folders have two files in it. Single dot and
// double dot.
return count(scandir($folder)) === 2;
};
var_dump($is_folder_empty('/tmp/demo'));
var_dump($is_folder_empty2('/tmp/demo'));
언급URL : https://stackoverflow.com/questions/7497733/how-can-i-use-php-to-check-if-a-directory-is-empty
'programing' 카테고리의 다른 글
| PHP에서 @ 연산자를 사용하여 오류 억제 (0) | 2023.02.03 |
|---|---|
| 경고: 헤더 정보를 수정할 수 없습니다. 헤더는 이미 ERROR에 의해 전송되었습니다. (0) | 2023.02.03 |
| Django에서 manage.py CLI를 사용하여 데이터베이스에서 모든 테이블을 삭제하려면 어떻게 해야 합니까? (0) | 2023.02.03 |
| 여러 Vue 애플리케이션, 여러 엔트리 파일, 동일한 Vuex/Vue3 Compostition Api 스토어 [반응성 상실] (0) | 2023.02.03 |
| @SmallTest, @Medium의 목적은 무엇입니까?Android에서 테스트 및 @LargeTest 주석을 사용하시겠습니까? (0) | 2023.02.03 |