Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent directory of running script

Tags:

directory

php

In PHP, what would be the cleanest way to get the parent directory of the current running script relative to the www root? Assume I have:

$_SERVER['SCRIPT_NAME'] == '/relative/path/to/script/index.php' 

Or just:

$something_else == '/relative/path/to/script/' 

And I need to get /relative/path/to/ with slashes properly inserted. What would you suggest? A one liner is preferred.

EDIT

I need to get a path relative to the www root, dirname(__FILE__) gives me an absolute path in the filesystem so that won't work. $_SERVER['SCRIPT_NAME'] on the other hand 'starts' at the www root.

like image 763
Tatu Ulmanen Avatar asked Dec 10 '09 16:12

Tatu Ulmanen


People also ask

How do I get the parent directory of a file?

Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.

How do I get parent directory in Python?

Get the Parent Directory in Python Using the path. parent() Method of the pathlib Module. The path. parent() method, as the name suggests, returns the parent directory of the given path passed as an argument in the form of a string.

How do I get parent directory in terminal?

The .. means “the parent directory” of your current directory, so you can use cd .. to go back (or up) one directory. cd ~ (the tilde). The ~ means the home directory, so this command will always change back to your home directory (the default directory in which the Terminal opens).

How do I show parent directory in Linux?

If you want to list contents of "above" working directory (parent directory) use: ls .. However, it shows both files and directories of the parent folder.


1 Answers

If your script is located in /var/www/dir/index.php then the following would return:

dirname(__FILE__); // /var/www/dir 

or

dirname( dirname(__FILE__) ); // /var/www 

Edit

This is a technique used in many frameworks to determine relative paths from the app_root.

File structure:

  /var/       www/           index.php           subdir/                  library.php 

index.php is my dispatcher/boostrap file that all requests are routed to:

define(ROOT_PATH, dirname(__FILE__) ); // /var/www 

library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

$path_current = dirname( __FILE__ ); // /var/www/subdir $path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir 

There's probably a better way to calculate the relative path then str_replace() but you get the idea.

like image 70
Mike B Avatar answered Sep 20 '22 11:09

Mike B