php如何检测目录是否存在,如何通过PHP检查目录是否存在?

inckie..

16

我认为realpath()可能是验证路径是否存在的最佳方法

http://www.php.net/realpath

这是一个示例函数:

/**

* Checks if a folder exist and return canonicalized absolute pathname (long version)

* @param string $folder the path being checked.

* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned

*/

function folder_exist($folder)

{

// Get canonicalized absolute pathname

$path = realpath($folder);

// If it exist, check if it's a directory

if($path !== false AND is_dir($path))

{

// Return canonicalized absolute pathname

return $path;

}

// Path/folder does not exist

return false;

}

相同功能的短版本

/**

* Checks if a folder exist and return canonicalized absolute pathname (sort version)

* @param string $folder the path being checked.

* @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned

*/

function folder_exist($folder)

{

// Get canonicalized absolute pathname

$path = realpath($folder);

// If it exist, check if it's a directory

return ($path !== false AND is_dir($path)) ? $path : false;

}

输出示例

/** CASE 1 **/

$input = '/some/path/which/does/not/exist';

var_dump($input); // string(31) "/some/path/which/does/not/exist"

$output = folder_exist($input);

var_dump($output); // bool(false)

/** CASE 2 **/

$input = '/home';

var_dump($input);

$output = folder_exist($input); // string(5) "/home"

var_dump($output); // string(5) "/home"

/** CASE 3 **/

$input = '/home/..';

var_dump($input); // string(8) "/home/.."

$output = folder_exist($input);

var_dump($output); // string(1) "/"

用法

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))

{

die('Folder ' . $path . ' already exist');

}

mkdir($folder);

// Continue do stuff

对于遇到此问题的任何人,我相信realpath会在文件夹运行时缓存它们,因此如果它运行一次,那么在此之后删除文件夹,如果再次运行它可能不会返回false. (2认同)

file_exists也是如此 (2认同)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值