Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php, realpath versus realpath + file_exists usage

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.

like image 404
AgelessEssence Avatar asked Dec 28 '22 10:12

AgelessEssence


1 Answers

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); //!


As a side note: realpath will never return a "FALSY" value. By this I mean that it will never return something which == FALSE but does not === FALSE (eg. NULL, '', 0, array()). Why? Well, the real path will always include a reference to the root — / in *nix systems (Mac, Unix, Linux) and C:\ in Windows, and those two strings will evaluate to true when used as a boolean (say in an if, while, or for loop). This means you can just do:
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
like image 79
cwallenpoole Avatar answered Jan 11 '23 21:01

cwallenpoole