How to get grandparent directory with PHP

I have the following directory structure.

-webshop -controllers -webshop.php 

In webshop.php I want to get an online store that is the progenitor of this file.

If I use the following, I think I get "controllers".

 echo basename(dirname(__FILE__)); // this will get controllers 

How can I get the grandparent directory?

Thanks in advance.

+4
source share
4 answers

dirname also works with directories, so you can get the parent of the parent, and then use the base name to get the base

 basename(dirname(dirname(__FILE__))); 

and test output

 kormoc@kormoc : /tmp/a/b/c > pwd /tmp/a/b/c kormoc@kormoc : /tmp/a/b/c > cat test.php <?php echo basename(dirname(dirname(__FILE__))); kormoc@kormoc : /tmp/a/b/c > php test.php b 
+5
source

This can also be done:

 echo basename(dirname(__DIR__, 2)); 

NOTE: THIS IS POSSIBLE ONLY IN PHP> = 7.0
The number of directory levels to be increased is the added functionality for dirname , which is a new feature in PHP 7. PHP5 did not implement such functionality.

http://php.net/manual/en/function.dirname.php

+1
source
 echo basename(dirname(__FILE__) . '/../..'); 
0
source

echo basename(__DIR__. "/../.."); If I remember it right.

PHP documentation:

__DIR__ File directory. If used inside 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 a root directory. (Added in PHP 5.3.0.)

0
source

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


All Articles