©
Dokumen ini menggunakan Manual laman web PHP Cina Lepaskan
(PHP 4, PHP 5, PHP 7)
is_file — 判断给定文件名是否为一个正常的文件
$filename
)判断给定文件名是否为一个正常的文件。
filename
文件的路径。
如果文件存在且为正常的文件则返回 TRUE
,否则返回 FALSE
。
Note: 因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型,对 2GB 以上的文件,一些文件系统函数可能返回无法预期的结果 。
Example #1 is_file() 例子
<?php
var_dump ( is_file ( 'a_file.txt' )) . "\n" ;
var_dump ( is_file ( '/usr/bin/' )) . "\n" ;
?>
以上例程会输出:
bool(true) bool(false)
失败时抛出 E_WARNING
警告。
Note: 此函数的结果会被缓存。参见 clearstatcache() 以获得更多细节。
自 PHP 5.0.0 起, 此函数也用于某些 URL 包装器。请参见 支持的协议和封装协议以获得支持 stat() 系列函数功能的包装器列表。
[#1] Anonymous [2014-03-02 21:13:53]
Please be aware wildcards do not work as one might expect.
<?php
$file = '*.*';
if ( is_file($file) ) {
echo( $file . ' is a regular file' );
} else {
echo( $file . ' is not a regular file' );
}
?>
The above snippet suggests that *.* is a regular file. It does not sound regular to me. I would expect is_file() to return FALSE.
[#2] sarken at free dot fr [2013-08-13 16:42:00]
I see, is_file not work properly on specifical file in /dev (linux)
look :
root@boofh:/data# php -r "var_dump(is_file('/dev/core'));"
bool(true)
root@boofh:/data# php -r "var_dump(is_file('/proc/kcore'));"
bool(true)
root@boofh:/data# ls -alh /proc/kcore
-r-------- 1 root root 128T Aug 13 18:39 /proc/kcore
OR FIND do not detect regular file.
root@boofh:/data# find /dev/ -type f
root@boofh:/data#
// version of php :
root@boofh:/data# php -v
PHP 5.4.4-14+deb7u3 (cli) (built: Jul 17 2013 14:54:08)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
[#3] david at bruchmann-web dot de [2013-05-10 17:36:56]
Today I got the in the comments already described behaviour that between directory and file can't be distinguished by is_file() or is_dir().
A dirty and incomplete hack is below, incomplete because it never includes links and I never tested what happens when a directory is not allowed to be read.
$items = scandir($dir);
foreach ($items as $item){
if ($item!='.' && $item!='..'){
$deep = @scandir($dir.'/'.$item);
echo ($deep ? '[DIR] ':'[FILE] '.$item.nl2br(PHP_EOL);
}
}
[#4] Anonymous [2012-02-06 19:44:34]
Note that is_file() returns false if the parent directory doesn't have +x set for you; this make sense, but other functions such as readdir() don't seem to have this limitation. The end result is that you can loop through a directory's files but is_file() will always fail.
[#5] Anonymous [2011-06-18 23:47:33]
is_file doesn't recognize files whose filenames contain strange characters like czech ? or russian characters in general.
I've seen many scripts that take it for granted that a path is a directory when it fails is_file($path). When trying to determine whether a path links to a file or a dir, you should always use is_dir after getting false from is_file($path). For cases like described above, both will fail.
[#6] don dot duvall at deduvall dot com [2009-09-11 14:55:35]
I have noticed that using is_file on windows servers (mainly for development) to use a full path c:\ doesn't always work.
I have had to use
C:/foldertowww/site/file.ext
so I preform an str_replace('\\', '/', $path)
Sometimes I have had the \ instead of / work. (this is using apache2 on XP)
but for sure you cannot have mixed separators.
[#7] ca dot redwood at gmail dot com [2009-04-23 12:24:30]
this is a simple way to find specific files instead of using is_file().
this example is made for mac standards, but easily changed for pc.
<?php
function isfile($file){
return preg_match('/^[^.^:^?^\-][^:^?]*\.(?i)' . getexts() . '$/',$file);
//first character cannot be . : ? - subsequent characters can't be a : ?
//then a . character and must end with one of your extentions
//getexts() can be replaced with your extentions pattern
}
function getexts(){
//list acceptable file extensions here
return '(app|avi|doc|docx|exe|ico|mid|midi|mov|mp3|
mpg|mpeg|pdf|psd|qt|ra|ram|rm|rtf|txt|wav|word|xls)';
}
echo isfile('/Users/YourUserName/Sites/index.html');
?>
[#8] Kevin Gregull [2008-11-13 08:14:45]
This Function deletes everything in a defined Folder:
Works with PHP 4 and 5.
<?php
function deletefolder($path)
{
if ($handle=opendir($path))
{
while (false!==($file=readdir($handle)))
{
if ($file<>"." AND $file<>"..")
{
if (is_file($path.'/'.$file))
{
@unlink($path.'/'.$file);
}
if (is_dir($path.'/'.$file))
{
deletefolder($path.'/'.$file);
@rmdir($path.'/'.$file);
}
}
}
}
}
?>
[#9] rigrace at swbell dot net [2008-10-09 21:48:17]
It took me a day or so to figure out that is_file() actually looks for a valid $ existing path/file in string form. It is not performing a pattern-like test on the parameter given. Its testing to see if the given parameter leads to a specific existing 'name.ext' or other (non-directory) file type object.
[#10] sy well-known-sign damla.net [2008-03-23 16:23:34]
In 32 bit environments, these functions including is_file(), stat() filesize() will not work due to PHPs default integer being signed. So anything above ~2.1 billion bytes you actually get a negative value.
This is actually a bug but I dont think there is an easy workaround. Try to switch to 64 bit.
[#11] gizmo at gizmo dot sk [2008-02-22 01:50:03]
here is a workaround for the file size limit. uses bash file testing operator, so it may be changed to test directories etc. (see http://tldp.org/LDP/abs/html/fto.html for possible test operators)
<?php
function is_file_lfs($path){
exec('[ -f "'.$path.'" ]', $tmp, $ret);
return $ret == 0;
}
?>
[#12] cristian dot ban at neobytesolutions com [2007-06-27 01:46:21]
regarding note from rehfeld dot us :
In my experience the best( and easiest ) way to find the extension of a file is :
<?php
// use this when you are sure it actually has an extension.
$extension = end(explode(".", $file_name));
?>
or
<?php
// this one will also check if it actually has an extension
$parts = explode(".", $file_name);
if (is_array($parts) && count($parts) > 1)
$extension = end($parts);
?>
[#13] tatarynowicz at gmail dot com [2006-10-17 19:35:48]
An easy way not to have to choose between hard-coding full paths and using relative paths is either via this line:
<?php
// in the bootstrap file
define('DIR_ROOT', dirname(__FILE__));
// in other files, prefix paths with the constant
require(DIR_ROOT . '/relative/to/bootstrap.php');
?>
or if you have to use a relative path:
<?php
require(dirname(__FILE__) . '/relative/to/this_file.php');
?>
This way all your paths will be absolute, yet you can move the application anywhere in the filesystem.
BTW, each successive call to dirname takes you one step up in the directory tree.
<?php
echo __FILE__;
// /www/site.com/public/index.php
echo dirname(__FILE__);
// /www/site.com/public
echo dirname(dirname(__FILE__));
// /www/site.com
?>
[#14] Jonathan Shaltz [2005-10-14 10:23:43]
Maybe this is a newbie mistake, but note that paths are relative to the filesystem and the location of the script. This means that MS IIS virtual directories are not available by relative path - use an absolute.
This threw me because virtual directories ARE available for URLs, at least on IIS.
[#15] bill fumerola [2005-08-30 18:45:03]
be careful, is_file() fails on files larger than your integer storage (2^32 for most).
Warning: is_file(): Stat failed for bigfile (errno=75 - Value too large for defined data type)
[#16] [2005-03-08 09:02:08]
### Symbolic links are resolved ###
If you pass a symlink (unix symbolic link) as parameter, is_file will resolve the symlink and will give information about the refered file. For example:
touch file
ln -s file link
echo '
<?php if (is_file("link")) echo "y\n"; ?>
' | php -q
will print "y".
is_dir resolves symlinks too.
[#17] ludvig dot ericson at gmail dot com [2004-10-25 11:06:47]
I tend to use alot of includes, and I found that the is_file is based on the script executed, not ran.
if you request /foo.php and foo.php looks like this:
<?php
include('foobar/bar.php');
?>
and bar.php looks like this:
<?php
echo (is_file('foo/bar.txt'));
?>
Then PHP (on win32, php 5.x) would look for /foo/bar.txt and not /foobar/foo/bar.txt.
you would have to rewrite the is_file statement for that, or change working directory.
Noting this since I sat with the problem for some time,
cheers, Toxik.
[#18] rehfeld.us [2004-09-03 15:04:17]
regarding rlh at d8acom dot com method,
It is incorrect. Well, it works but you are not guaranteed the file extension using that method.
for example : filename.inc.php
your method will tell you the ext is "inc", but it is in fact "php"
heres a way that will work properly.
<?php
$dh = opendir($dir);
while (false !== ($document = readdir($dh))) {
$pos = strrpos($document, '.');
if (false !== $pos && strlen($document) > $pos + 1) {
$ext = substr($document, $pos + 1);
}
}
?>
[#19] rlh at d8acom dot com [2003-02-12 05:17:34]
I do a lot of file parsing and have found the following technique extremely useful:
while (false !== ($document = readdir($my_dir)))
{
$ext=explode('.',$document);
if($document != '.' && $document != '..' && $ext[1])
{
'Do something to file...'
}
}
It gets around the fact that, when working on website pages, the html files are read as directories when downloaded. It also allows you to extend the usefulness of the above method by adding the ability to determine file types e.g.
if($document != '.' && $document != '..' && $ext[1]=='htm')
or
if($document != '.' && $document != '..' && $ext[1]=='doc')
[#20] andreas dot stagl at fits dot at [2002-03-27 11:34:14]
if you're running apache as a service on a win32 machine, an you try to determinate if a file on an other pc in your network exists - ex.: is_file('//servername/share/dir1/dir2/file.txt') - you may return false when you're running the service as LocalSystem. To avoid this, you have to start the Apache-Service as a 'registered' domain user.
[#21] quietust at ircN dot org [2001-12-13 20:20:43]
In PHP 4.1.0 under win32, this seems to print out a warning message if the file does not exist (using error_reporting = E_ALL & ~E_NOTICE).