简体   繁体   English

检查PHP中是否存在目录

[英]Check whether a directory exists in PHP

I know, I know , this sounds soo easy.我知道,我知道,这听起来容易。 But I can't seem to find the correct answer on the Internet.但我似乎无法在互联网上找到正确的答案。

One of the solution I found was to use is_dir .我找到的解决方案之一是使用is_dir

if(is_dir($dir))
  echo 'directory exists';
else
  echo 'drectory not exist';

But this is wrong -- All this function does is to check whether the $dir is a directory, it doesn't check whether the directory exists, or not.但这是错误的——这个函数所做的只是检查$dir是否是一个目录,它不检查该目录是否存在。 In other words if I put:换句话说,如果我把:

$rootDir = "C:\\Documents and Settings\\test\\My Documents\\Image Directory\\Me Dog\\";

then the function will return a true, even though you can find no such directory on your web server.那么该函数将返回一个 true,即使您在您的 Web 服务器上找不到这样的目录。

Any ideas?有任何想法吗?

Should work correctly.应该可以正常工作。 From is_dir() documentation:is_dir()文档:

Returns TRUE if the filename exists and is a directory , FALSE otherwise.如果文件名存在并且是一个目录,则返回 TRUE,否则返回 FALSE。

Well, anyway if it doesn't try this:好吧,无论如何,如果它不尝试这个:

if(file_exists($dir) && is_dir($dir))

BTW.顺便提一句。 results of these functions are cached in stat cache.这些函数的结果缓存在 stat 缓存中。 Use clearstatcache() to clean that cache.使用clearstatcache()清理该缓存。

You'll probably want to use opendir() after is_dir() agrees that the path (could) be a directory.在 is_dir() 同意路径(可以)是目录之后,您可能想要使用opendir()

If the resource returned by opendir() is valid, you know you have a directory, and already have a handle to read it.如果 opendir() 返回的资源有效,则您知道您有一个目录,并且已经有一个句柄可以读取它。

Just be sure to call closedir(), either way, if a valid handle is returned.如果返回有效句柄,请务必调用 closedir(),无论哪种方式。

Edit:编辑:

This answer assumes that you'll be opening the directory either way.此答案假定您将以任何一种方式打开目录。 If you just need to ensure a path is sane / valid, file_exists() is much cheaper.如果您只需要确保路径健全/有效,file_exists() 便宜得多。

bool file_exists ( string $filename )

Checks whether a file or directory exists.检查文件或目录是否存在。

http://php.net/manual/en/function.file-exists.php http://php.net/manual/en/function.file-exists.php

You could try this:你可以试试这个:

if(is_dir($dir) && is_writeable($dir))
{
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM