伍佰目录 短网址
  当前位置:海洋目录网 » 站长资讯 » 站长资讯 » 文章详细 订阅RssFeed

PHP - Manual: is_dir

来源:网络转载 浏览:64次 时间:2022-11-22
is_executable » « glob PHP 手册 函数参考 文件系统相关扩展 文件系统 文件系统函数

is_dir

(PHP 4, PHP 5, PHP 7, PHP 8)

is_dir — 判断给定文件名是否是一个目录

说明

is_dir(string $filename): bool

判断给定文件名是否是一个目录。

参数

filename

如果文件名存在并且为目录则返回 true。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。 If filename is a symbolic or hard link then the link will be resolved and checked.If you have enabled open_basedir further restrictions may apply.

返回值

如果文件名存在,并且是个目录,返回 true,否则返回false

范例

示例 #1 is_dir() 例子

<?php
var_dump(is_dir('a_file.txt'));
var_dump(is_dir('bogus_dir/abc'));

var_dump(is_dir('..')); //one dir up
?>

以上例程会输出:

bool(false)
bool(false)
bool(true)

错误/异常

失败时抛出E_WARNING警告。

注释

注意: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。

小技巧

自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。

参见

chdir() - 改变目录 dir() - 返回一个 Directory 类实例 opendir() - 打开目录句柄 is_file() - 判断给定文件名是否为一个正常的文件 is_link() - 判断给定文件名是否为一个符号连接
add a note

User Contributed Notes 20 notes

up down 16 digitalaudiorock at gmail dot com12 years ago Just a note for anyone who encounters is_dir() returning false on CIFS mount points or directories within those mount points on 2.6.31 and newer kernels: Apparently in new kernels they've started using the CIFS serverino option by default.  With Windows shares this causes huge inode numbers and which apparently can cause is_dir() to return false.  Adding the noserverino option to the CIFS mount will prevent this.  This may only occur on 32 systems but I don't have a 64 bit install to test against. up down 12 thomas at thomasnoest dot nl6 years ago Note that on Linux is_dir returns FALSE if a parent directory does not have +x (executable) set for the php process. up down 11 sly at noiretblanc dot org18 years ago This is the "is_dir" function I use to solve the problems :

function Another_is_dir ($file)
{
    if ((fileperms("$file") & 0x4000) == 0x4000)
        return TRUE;
    else
        return FALSE;
}

or, more simple :

function Another_is_dir ($file)
{
return ((fileperms("$file") & 0x4000) == 0x4000);
}

I can't remember where it comes from, but it works fine.
up down 8 jonlulf at gmail dot com6 years ago My solution to the problem that you must include the full path to make "is_dir" work properly as a complete example:

    <? // findfiles.php  -  what is in directory "videoarchive"
    $dir    = 'images/videoarchive/'; // path from top
    $files = scandir($dir);
    $files_n = count($files);

   
    $i=0;
    while($i<=$files_n){
        // "is_dir" only works from top directory, so append the $dir before the file
        if (is_dir($dir.'/'.$files[$i])){  
            $MyFileType[$i] = "D" ; // D for Directory
        } else{
            $MyFileType[$i] = "F" ; // F for File
        }
        // print itemNo, itemType(D/F) and itemname
        echo '<br>'.$i.'. '. $MyFileType[$i].'. ' .$files[$i] ;
        $i++;
    }
    ?>
up down 5 Anonymous14 years ago One note regarding checking for empty directories :
>>echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
This does not work correctly on Linux.
The '.' and '..' will always be returned even if no files are present in the directory.
up down 3 Bjrn K.6 years ago Note that this functions follows symbolic links. It will return true if the file is actually a symlink that points to a directory.

An example:
<php
symlink(".", "testlink");
var_dump(is_dir("testlink"));
unlink("testlink");
?>

Prints out:
bool(true)

(Windows Note: Under recent versions of Windows you can set symlinks as long as you're administrator, but you cannot remove directory symlinks with "unlink()", you will have to use "rmdir testlink" from the shell to get rid of it.)
up down 3 danr at cvisual dot com dot com14 years ago Running PHP 5.2.0 on Apache Windows, I had a problem (likely the same one as described by others) where is_dir returned a False for directories with certain permissions even though they were accessible.

Strangely, I was able to overcome the problem with a more complete path. For example, this only displays "Works" on subdirectories with particular permissions (in this directory about 1 out of 3):

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        if(is_dir($f)) {
            echo "<b>Works:" . $f . "</b>";
        }
}

However, this works properly for all directories:

$d = opendir("./albums/mydir");
while(false !== ($f = readdir($d))) {
    echo "<hr />";
        $dName = "./albums/mydir/" . $f;
        if(is_dir($dName)) {
            echo "<b>Works:" . $dName . "</b>";
        }
}

I don't understand the hit-and-miss of the first code, but maybe the second code can help others having this problem.
up down 2 vstoykov at consultant dot bg13 years ago When trying (no 'pear') to enumerate mounted drives on a win32  platform (Win XP SP3, Apache/2.2.11, PHP/5.2.9), I used:

<?php
function echo_win_drives() {

  for($c='A'; $c<='Z'; $c++)
    if(is_dir($c . ':'))
      echo $c . ': ';
}
?>

which yielded:
A: C: D: E: F: G: H: I:
up down 1 niceuser at live dot com9 years ago PITFALL in sub dir processing

After struggeling with a sub-dir processing (some subdirs were skipped) AND reading the posts, I realized that virutally no-one clearly told what were wrong.

The common traverse dir code was:
-----------------------------------------

opendir("myphotos"); // Top dir to process from (example)

while (false !== ($fname = readdir($h_dir))) { // process current dir (read a directory entry)

   if ($fname{0} == '.') continue; // skip dirs . and .. by first char test

   if (is_dir($fname)) call_own_subdir_process;  // process this subdir by calling a routine

   }

PROBLEM IS :

The "is_dir()" must have the FULL PATH or it will skip some dirs. So the above code need to INSERT THE PATH before the filename. This would give this change in above...

   if (is_dir("myphotos\" . $fname)) call_own_subdir_process;  // skip subdirs

The pitfall really was, that without full path some subdirs were found...hope this clears all up
up down 1 jerome dot pros at gmail dot com3 years ago Note that is_dir() also works with ftp://.

For example :

<?php
if(is_dir('ftp://user:pass@host/www/path/to/your/folder')) {
    // Your code.
}
?>

But note that if the connexion fails due to invalide credentials, this will consider that the folder doesn't exist and will return FALSE.
up down 0 gecko4 at gmail dot com15 years ago Here is another way to test if a directory is empty, which I think is much simpler than those posted below:

<?php
$dir = 'directory';
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
up down 0 Eric15 years ago Ah ha!  Maybe this is a bug, or limitation to be more precise, of php. See http://bugs.php.net/bug.php?id=27792

A workaround is posted on the page (above) and seems to work for me:

function is_dir_LFS($path){
  return (('d'==substr(exec("ls -dl '$path'"),0,1))?(true):(false));
}

PS: I'm using PHP 4.3.10-16, posts report this problem up to 5.0
up down -1 citizenmarco at gmail dot com5 years ago Note that there quite a few articles on the net that imply that commands like is_dir, opendir, readdir cannot read paths with spaces.

On a linux box, THAT is not an issue.

Sample test code;

$dir = "Images/Soma ALbum Name with spaces";
    

echo $dir."<br/>";

// Open a directory, and read its contents
if (is_dir($dir)){
  echo $dir."<br/>"; // will not appear if above fails
    if ($dh = opendir($dir)){
      echo $dir."<br/>"; // will not appear if above fails
      while (($file = readdir($dh)) !== false){
        echo "filename:" . $file . "<br>";
        echo $dir."<br/>"; // will not appear if above fails
      }
      closedir($dh);
    }
}
up down -2 puremango dot co dot uk at gmail dot com17 years ago this function bypasses open_basedir restrictions.
<?
function my_is_dir($dir)
{
    // bypasses open_basedir restrictions of is_dir and fileperms
    $tmp_cmd = `ls -dl $dir`;
    $dir_flag = $tmp_cmd[0];
    if($dir_flag!="d")
    {
        // not d; use next char (first char might be 's' and is still directory)
        $dir_flag = $tmp_cmd[1];
    }
    return ($dir_flag=="d");
}
?>

example:
<?
....
echo is_dir("/somewhere/i/dont/have/access/to");
?>
output:
Warning: open_basedir restriction in effect

<?
....
echo my_is_dir("/somewhere/i/dont/have/access/to");
?>
output:
true (or false, depending whether it is or not...)

---
visit puremango.co.uk for other such wonders
up down -1 Victor9 years ago If you are using Mac, or others systems that store information about the directory layout and etc, the function:

   function empty_dir($dir) {
        if (($files = @scandir($dir)) && count($files) <= 3)
            return true;
        else
            return false;
    }

Must have the count($files) comparing with the number of hidden files!

For example, I'm using Mac and the empty directory shows me three files: ".", ".." and ".DS_Store", so if I am planning to put the website online on my Mac, I've to count in the ".DS_Store" file!
up down -2 jasoneisen at gee mail13 years ago An even better (PHP 5 only) alternative to "Davy Defaud's function":

<?php
function is_empty_dir($dir)
{
    if (($files = @scandir($dir)) && count($files) <= 2) {
        return true;
    }
    return false;
}
?>

NOTE: you should obviously be checking beforehand if $dir is actually a directory, and that it is readable, as only relying on this you would assume that in both cases you have a non-empty readable directory.
up down -3 tibard at gmail dot com17 years ago use this function to get all files inside a directory (including subdirectories)

<?php
function scan_Dir($dir) {
    $arrfiles = array();
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            chdir($dir);
            while (false !== ($file = readdir($handle))) {
                if ($file != "." && $file != "..") {
                    if (is_dir($file)) {
                        $arr = scan_Dir($file);
                        foreach ($arr as $value) {
                            $arrfiles[] = $dir."/".$value;
                        }
                    } else {
                        $arrfiles[] = $dir."/".$file;
                    }
                }
            }
            chdir("../");
        }
        closedir($handle);
    }
    return $arrfiles;
}

?>
up down -5 Btx13 years ago <?php
public static function isEmptyDir($dir){
     return (($files = @scandir($dir)) && count($files) <= 2);
}
?>

better ;)
up down -6 alanguir at detroitchamber dot com13 years ago When I run a scandir I always run a simple filter to account for file system artifacts (especially from a simple ftp folder drop) and the "." ".." that shows up in every directory:

<?php
    if (is_dir($folder){
        $contents = scandir($folder);
        $bad = array(".", "..", ".DS_Store", "_notes", "Thumbs.db");
        $files = array_diff($contents, $bad);
    }
?>
up down -5 Anonymous17 years ago Unfortunately, the function posted by p dot marzec at bold-sg dot pl does not work.
The corrected version is:

// returns true if folder is empty or not existing
// false if folde is full

function is_empty_folder($dir) {
if (is_dir($dir)) {
   $dl=opendir($dir);
   if ($dl) {
       while($name = readdir($dl)) {
   if (!is_dir("$dir/$name")) { //<--- corrected here
       return false;
       break;
       }
   }
       closedir($dl);
       }
   return true;
   } else return true;
}
add a note

官方地址:https://www.php.net/manual/en/function.is-dir.php

  推荐站点

  • At-lib分类目录At-lib分类目录

    At-lib网站分类目录汇集全国所有高质量网站,是中国权威的中文网站分类目录,给站长提供免费网址目录提交收录和推荐最新最全的优秀网站大全是名站导航之家

    www.at-lib.cn
  • 中国链接目录中国链接目录

    中国链接目录简称链接目录,是收录优秀网站和淘宝网店的网站分类目录,为您提供优质的网址导航服务,也是网店进行收录推广,站长免费推广网站、加快百度收录、增加友情链接和网站外链的平台。

    www.cnlink.org
  • 35目录网35目录网

    35目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向35目录推荐、提交优秀网站。

    www.35mulu.com
  • 就要爱网站目录就要爱网站目录

    就要爱网站目录,按主题和类别列出网站。所有提交的网站都经过人工审查,确保质量和无垃圾邮件的结果。

    www.912219.com
  • 伍佰目录伍佰目录

    伍佰网站目录免费收录各类优秀网站,全力打造互动式网站目录,提供网站分类目录检索,关键字搜索功能。欢迎您向伍佰目录推荐、提交优秀网站。

    www.wbwb.net