java realpath vs absolute path_php 实例之使用realpath()检查目录是否存在

is_dir和file_exists函数都可以用来检测目录是否存在,但小编认为php检查目录是否存在最好的方法是使用realpath()函数,下面我们来看一下如何使用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;

}

测试实例:

/** 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"

/* http://www.manongjc.com/article/1419.html */

/** 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值