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.
Use File 's getParentFile() method and String. lastIndexOf() to retrieve just the immediate parent directory.
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.
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).
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.
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
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.
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