php file_exists is_file is_dir函数效率实例详解

时间:2016-08-15
php file_exists函数用于判断文件或目录是否存在,is_file函数只用于判断文件是否存在,而is_dir则只用于判断目录是否存在,本文章向大家介绍这三个函数的基本使用实例及区别,需要的朋友可以参考一下。

file_exists

file_exists — 检查文件或目录是否存在。 从表面意思来看,file_exists函数是检查文件是否存在,其实该函数也可以用于检测目录是否存在。因此,其效率比is_file低得多。

语法:

bool file_exists ( string $filename )

参数

  1. filename 文件或目录的路径。 

实例: 

<?php
$filename = '/path/to/foo.txt';
/* http://www.manongjc.com/article/1354.html */
if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
?> 

is_file

is_file — 判断给定文件名是否为一个正常的文件,该函数只能用于判断文件是否存在,因此其效率比file_exists高得多

语法:

bool is_file ( string $filename ) 

参数:

  1. filename 文件的路径。 

实例:

<?
if ( is_file( "data.txt" ) ) {
  print "test.txt is a file!";
}
?>

is_dir

is_dir — 判断给定文件名是否是一个目录,该函数只能判断是否为目录,上面已经说过file_exists函数也可以判断是否为目录,但是is_dir比file_exists效率要高。

语法:

bool is_dir ( string $filename )

参数:

  1. filename 如果文件名存在并且为目录则返回 TRUE。如果 filename 是一个相对路径,则按照当前工作目录检查其相对路径。 If filename is a symbolic or hard link then the link will be resolved and checked. If you have enabled 安全模式, or open_basedir further restrictions may apply. 

实例: 

bool is_dir (string filename)

<?
    $isdir = is_dir("index.html"); // returns false
    
    $isdir = is_dir("book"); // returns true
?>

file_exists is_file is_dir总结:

is_file 只判断文件是否存在; 
file_exists 判断文件是否存在或者是目录是否存在; 
is_dir 判断目录是否存在;

如果要判断目录是否存在,请用独立函数 is_dir(directory) 
如果要判断文件是否存在,请用独立函数 is_file(filepath)