How can I return the pathname from the current file, only 2 directories up?
So if I my current file URL is returning theme/includes/functions.php
How can I return "theme/"
Currently I am using
return dirname(__FILE__)
dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap. php resides.
If you are using PHP 7.0 and above then the best way to navigate from your current directory or file path is to use dirname(). This function will return the parent directory of whatever path we pass to it.
__FILE__ is simply the name of the current file. realpath(dirname(__FILE__)) gets the name of the directory that the file is in -- in essence, the directory that the app is installed in. And @ is PHP's extremely silly way of suppressing errors.
The dirname() function in PHP is an inbuilt function which is used to return the directory name of a given path. The dirname() function is used to parent directory's path i.e levels up from the current directory.
PHP 5.3+
return dirname(__DIR__);
PHP 5.2 and lower
return dirname(dirname(__FILE__));
With PHP7 go further up the directory tree by specifying the 2nd argument to dirname
. Versions prior to 7 will require further nesting of dirname
.
http://php.net/manual/en/function.dirname.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With