Home » Php » php – Get 2 levels up from dirname( __FILE__)

php – Get 2 levels up from dirname( __FILE__)

Posted by: admin April 23, 2020 Leave a comment

Questions:

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__)
How to&Answers:

PHP 7

return dirname(__FILE__, 2);

PHP 4 and higher

return dirname(dirname(__FILE__));

With PHP7 you can get further up the directory tree by specifying the levels parameter, while pre-7 PHP will require further nesting of the dirname function.

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

Answer:

Even simpler than dirname(dirname(__FILE__)); is using __DIR__

dirname(__DIR__);

which works from php 5.3 on.

Answer:

[ web root ]
    / config.php
    [ admin ] 
        [ profile ] 
            / somefile.php 

How can you include config.php in somefile.php? You need to use dirname with 3 directories structure from the current somefile.php file.

require_once dirname(dirname(dirname(__FILE__))) . '/config.php'; 

dirname(dirname(dirname(__FILE__))) . '/config.php'; # 3 directories up to current file

Answer:

Late to the party, but you can also do something like below, using \..\..\ as many times as needed to move up directory levels.

$credentials = require __DIR__ . '\..\App\Database\config\file.php';

Which is the equivalent to:

$credentials = dirname(__DIR__) . '\App\Database\config\file.php';

The benefit being is that it avoids having to nest dirname like:

dirname(dirname(dirname(__DIR__))

Note, that this is tested on a IIS server – not sure about a linux server, but I don’t see why it wouldn’t work.

Answer:

As suggested by @geo, here’s an enhanced dirname function that accepts a 2nd param with the depth of a dirname search:

/**
 * Applies dirname() multiple times.
 * @author Jorge Orpinel <[email protected]>
 * 
 * @param string $path file/directory path to beggin at
 * @param number $depth number of times to apply dirname(), 2 by default
 * 
 * @todo validate params
 */
function dirname2( $path, $depth = 2 ) {

    for( $d=1 ; $d <= $depth ; $d++ )
        $path = dirname( $path );

    return $path;
}

Note: that @todo may be relevant.

The only problem is that if this function is in an external include (e.g. util.php) you can’t use it to include such file :B

Answer:

require_once(dirname(__FILE__) . "/../../functions.php");

Answer:

This is an old question but sill relevant.

Use:

basename(dirname(__DIR__));

to return just the second parent folder name – “theme” in this case.

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