php 实例之使用realpath()检查目录是否存在

时间:2016-08-30
php检查目录是否存在一般可以使用is_dir或file_exists,但realpath函数也可以实现判断目录是否存在,本文章向大家介绍realpath()检查目录是否存在的实例源码,需要的朋友可以参考一下。

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