Reputation: 6731
by performance reasons we should use only realpath() instead of realpath() + file_exists() when checking existence of a file or directory ??
CASE A ::
if(realpath(__DIR__."/../file.php")===false)
CASE B ::
if(file_exists(realpath(__DIR__."/../file.php"))===false)
i think CASE A
do the job, and CASE B
do the job two times.
Upvotes: 5
Views: 3760
Reputation: 82028
Not only is case B redundant (as realpath returns false if the path cannot be resolved or the file does not exist as per the docs), if the file does not exist, that is a bit silly.
Since this statement will return FALSE
:
realpath(__DIR__."/../file.php");
This:
file_exists(realpath(__DIR__."/../file.php"));
Is really this:
file_exists(FALSE); //!
if(!realpath(__DIR__."/../file.php")) // do something
Or, if you need to actually have the realpath, you can:
if(!($path = realpath(__DIR__."/../file.php")))
// file does not exist
else
// $path is now the full path to the file
Upvotes: 9
Reputation: 3633
They are nearly the same, but not exactly!
Case A will check if the path exists, realpath
will return non-false values if the path after expanding it will point to a file or folder. Also if you pass realpath
a null
-value or an empty string it will return the current folder.
Case B can also check if the returned path is a regular file (as opposed to a directory!). If realpath resolves the path to an folder, an is_file
call will return false
and you can handle it from there.
So realpath
will check if there is a file or folder (or symlink link thereto) at the given path and will expand empty values to the current directory. The extra is_file
check can ensure you're working with a file not a folder.
Use case B (with is_file
instead of file_exists
) if you want to be sure you're working with a file, use case A if folders are also okay. :)
file_exists
(in contrast with is_file
) returns true
for directories as well.
Upvotes: 1
Reputation: 9547
That is correct. realpath() will return false if the file does not exist. Case B is redundant.
https://www.php.net/realpath#refsect1-function.realpath-returnvalues
Upvotes: 2