检查某个目录是否存在于 PHP 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/746672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether a Directory Exists in PHP
提问by Graviton
I know, I know, this sounds sooeasy. 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 $diris a directory, it doesn't check whether the directory exists, or not. In other words if I put:
但这是错误的——这个函数所做的只是检查是否$dir是一个目录,它不检查目录是否存在。换句话说,如果我把:
$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?
有任何想法吗?
回答by vartec
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. Use clearstatcache()to clean that cache.
顺便提一句。这些函数的结果缓存在 stat 缓存中。使用clearstatcache()清理该缓存。
回答by Tim Post
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() 便宜得多。
回答by Bart S.
You could try this:
你可以试试这个:
if(is_dir($dir) && is_writeable($dir))
{
// ...
}
回答by madhu
bool file_exists ( string $filename )
Checks whether a file or directory exists.
检查文件或目录是否存在。

