is_dir和file_exists函数都可以用来检测目录是否存在,但小编认为php检查目录是否存在最好的方法是使用realpath()函数,下面我们来看一下如何使用realpath()函数实现检查目录是否存在。
<?php
/**
* 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;
}
测试实例:
<?php
/** 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) \"/\"
使用实例:
<?php
$folder = \'/foo/bar\';
if(FALSE !== ($path = folder_exist($folder)))
{
die(\'Folder \' . $path . \' already exist\');
}
mkdir($folder);
// Continue do stuff 继续阅读与本文标签相同的文章
下一篇 :
语音搜索时代,如何利用智能音箱卖货
-
PS保存图片提示“无法完成请求”,这里有4种解决方法!
2026-05-14栏目: 教程
-
想买1000元左右的5G手机?我们需要等多久?
2026-05-14栏目: 教程
-
剧情反转?美企主动购买华为5G技术,华为成赞赏排行榜第一名!
2026-05-14栏目: 教程
-
城市数字化后,新一代内生安全系统可全方位保护
2026-05-14栏目: 教程
-
谷歌也来“唱衰”5G,5G手机只会徒增功耗?为何这么说?
2026-05-14栏目: 教程
