如果目录还不存在,我想创建一个目录。
为此,使用is_dir
函数就足够了吗?
if ( !is_dir( $dir ) ) {
mkdir( $dir );
}
或者我应该将is_dir
与file_exists
结合使用
if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
mkdir( $dir );
}
发布于 2011-03-25 05:42:07
在Unix系统上,两者都会返回true --在Unix中,所有东西都是一个文件,包括目录。但要测试该名称是否被采用,您应该同时检查这两个名称。可能有一个名为'foo‘的常规文件,它会阻止您创建一个名为'foo’的目录。
发布于 2011-06-08 18:50:02
$dirname = $_POST["search"];
$filename = "/folder/" . $dirname . "/";
if (!file_exists($filename)) {
mkdir("folder/" . $dirname, 0777);
echo "The directory $dirname was successfully created.";
exit;
} else {
echo "The directory $dirname exists.";
}
发布于 2013-12-22 04:55:47
我认为realpath()可能是验证路径是否存在http://www.php.net/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
/**
* 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;
}
输出示例
<?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"
/** 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
https://stackoverflow.com/questions/5425891
复制相似问题