Using php, realpath and realpath + file_exists

for performance reasons, we should use realpath () instead of realpath () + file_exists () when checking for 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 will complete the task, and CASE B will complete the task two times.

+4
source share
3 answers

Not only case B has been reserved (since realpath returns false if the path cannot be resolved or the file does not exist according to docs ), if the file does not exist, this is a little silly.

Since this statement will return FALSE :

 realpath(__DIR__."/../file.php"); 

It:

 file_exists(realpath(__DIR__."/../file.php")); 

Is it really:

 file_exists(FALSE); //! 


As a side note: realpath will never return "FALSY". By this, I mean that it will never return what == FALSE , but not === FALSE (e.g. NULL , '' , 0, array ()). What for? Well, the real path will always include a link to root - / on * nix systems (Mac, Unix, Linux) and C:\ on Windows, and these two lines will evaluate to true when used as a logical one (for example, in an if loop, while or for). This means that you can simply do:
 if(!realpath(__DIR__."/../file.php")) // do something 

Or, if you need to have a real path, you can:

 if(!($path = realpath(__DIR__."/../file.php"))) // file does not exist else // $path is now the full path to the file 
+7
source

It is right. realpath () will return false if the file does not exist. Case B is redundant.

http://us3.php.net/realpath#refsect1-function.realpath-returnvalues

+2
source

They are almost the same, but not quite!

Case A checks if the path exists, realpath returns invalid values ​​if the path after its extension points to a file or folder . Also, if you pass a realpath a null value or an empty string, it will return the current folder.

Case B can also check if the return path is a regular file (as opposed to a directory!). If realpath resolves the path to the folder, calling is_file returns false , and you can process it from there.

So realpath will check if there is a file or folder (or symlink to it) along this path and will propagate empty values ​​to the current directory. An additional check for is_file can ensure that you are working with a file, not a folder.

Use case B (with is_file instead of file_exists ), if you want to be sure that you are working with the file, use case A if the folders are ok too. :)

file_exists (unlike is_file ) returns true for directories.

+1
source

Source: https://habr.com/ru/post/1384544/


All Articles