Home » Php » php – Is "realpath" redundant in $absolutePath = realpath(__DIR__)? Is __DIR__ always canonical absolute path?

php – Is "realpath" redundant in $absolutePath = realpath(__DIR__)? Is __DIR__ always canonical absolute path?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Is it a sence to do something like

 $dir = realpath(dirname(__FILE__));
 // or for php 5.3+:
 $dir = realpath(__DIR__)

Or magic constants like DIR and FILE always returns absolute path, so realpath is redundant?

How to&Answers:

You don’t need realpath().

The documentation of __FILE__:

The full path and filename of the file. If used inside an include, the
name of the included file is returned. Since PHP 4.0.2, __FILE__
always contains an absolute path with symlinks resolved whereas in
older versions it contained relative path under some circumstances.

So __FILE__ returns an absolute path => realpath() unnecessary

And if you use __DIR__:

The directory of the file. If used inside an include, the directory of
the included file is returned. This is equivalent to
dirname(__FILE__)
. This directory name does not have a trailing slash
unless it is the root directory. (Added in PHP 5.3.0.)

__DIR__ also returns an absolute path because dirname() doesn’t cut off the absolute part of the path of __FILE__ => realpath() unnecessary