In php whether file_exists or is_file is used to determine the existence of the file

  • 2020-05-24 05:16:20
  • OfStack

After reading the difference between file_exists and is_file,is_dir in PHP, it is clear that file_exists of PHP = is_dir + is_file.

Write program verification 1:

Execute 1000 times respectively and record the required time.

File exists (current directory)
is_file:0.4570ms
file_exists:2.0640ms

File exists (absolute path layer 3 /www/hx/a/)
is_file:0.4909ms
file_exists:3.3500ms

The absolute path to the file exists (5 layer/www hx/a b/c /)
is_file:0.4961ms
file_exists:4.2100ms

File does not exist (current directory)
is_file:2.0170ms
file_exists:1.9848ms

The absolute path to the file does not exist (5 layer/www hx/a b/c /)
is_file:4.1909ms
file_exists:4.1502ms

Directory exists
file_exists:2.9271ms
is_dir:0.4601ms
Directory does not exist
file_exists:2.9719ms
is_dir:2.9359ms

is_file($file)
file_exists($file)
When $file is a directory, is_file returns false, file_exists returns true

If the file exists, is_file is much faster than file_exists;
The deeper the directory where you want to detect the file, the greater the difference in speed, but at least four times faster.

In the absence of a file, is_file is 1 point slower than file_exists, but it is negligible.

If the directory exists, is_dir is much faster than file_exists;
In the absence of a directory, is_dir is a bit slower than file_exists, but it is negligible.

Conclusion:

If you want to determine whether the file exists, use the function is_file(),
To determine if a directory exists, use the function is_dir(),
It seems that there is no place to use file_exists, when you are not sure whether the parameter passed in is a file or a directory?

Related articles: