首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何检查目录是否存在?"is_dir“、"file_exists”还是两者兼而有之?

如何检查目录是否存在?"is_dir“、"file_exists”还是两者兼而有之?
EN

Stack Overflow用户
提问于 2011-03-25 05:38:13
回答 9查看 414K关注 0票数 369

如果目录还不存在,我想创建一个目录。

为此,使用is_dir函数就足够了吗?

if ( !is_dir( $dir ) ) {
    mkdir( $dir );       
}

或者我应该将is_dirfile_exists结合使用

if ( !file_exists( $dir ) && !is_dir( $dir ) ) {
    mkdir( $dir );       
} 
EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2011-03-25 05:42:07

在Unix系统上,两者都会返回true --在Unix中,所有东西都是一个文件,包括目录。但要测试该名称是否被采用,您应该同时检查这两个名称。可能有一个名为'foo‘的常规文件,它会阻止您创建一个名为'foo’的目录。

票数 246
EN

Stack Overflow用户

发布于 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.";
}
票数 144
EN

Stack Overflow用户

发布于 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
票数 21
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5425891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档