Reputation: 1669
I have this which is probably a roundabout way of finding the path:
<?php require_once $parent_dir = dirname(dirname(dirname($_SERVER['SCRIPT_FILENAME']))).'/myFile.php'; ?>
It works, but is there a cleaner way of writing it?
My site has a subdomain. Here's where myFile.php is located:
Upvotes: 0
Views: 3170
Reputation: 322
Maybe after more than 10 years, it may still help someone else.
If you need to find the top-level directory from whatever path, you can do it with one single line of code:
$top_level_dirname = dirname( $path,substr_count( $path,'/' ) );
The function dirname accepts as a second argument (not required, and 1 as default) the number of parent directories to go up. So, if you set that argument to the number of occurrences of "/", you will go up to the top.
Example:
$path = '/htdocs/public';
echo dirname( $path,substr_count( $path,'/' ); // will echo 'htdocs'
$path = '/htdocs/public/other_name';
echo dirname( $path,substr_count( $path,'/' ); // will still echo 'htdocs'
Upvotes: 0
Reputation: 14479
I'm also not exactly sure what you're trying to do, but perhaps something like this will shorten it for you:
$pathArr = explode("/", __DIR__);
var_dump($pathArr);
// previous was for debugging to see what gets put where, remove this once you sort it out.
// list($level1, $level2, ...) = explode("/", __FILE__);
Upvotes: 1
Reputation: 193291
Sometimes getcwd
can be useful:
require_once getcwd() . '/../../myFile.php' ;
Upvotes: 0
Reputation: 3377
If you have PHP 5.3 (or above), you can use __DIR__
:
$parent_dir = __DIR__.'/../myFile.php';
Your example seems to go a couple levels further up, so you can add to that:
$parent_dir = __DIR__.'/../../myFile.php';
__DIR__
is a magic constant that evaluates to the directory the file that calls it is located.
And as highlighted in the other answer, if you're after the root, $_SERVER[DOCUMENT_ROOT]
will give you the path as defined in your server (eg. Apache) config.
Upvotes: 0
Reputation: 309
I'm not sure what exactly you are trying to do, but maybe $_SERVER['DOCUMENT_ROOT']
may help you.
Upvotes: 1