tags:

views:

424

answers:

3

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.

+2  A: 

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.

Mike B
That won't work as I need the path relative to the www root. I could just replace the /var/www part out of it, but this needs to work on Windows and *nix.
Tatu Ulmanen
There is no dependable sure-fire way of determining the ROOT_PATH on all OS's on all servers. The best practice technique is to `define(ROOT_PATH, dirname(__FILE__));` early in your stack (hopefully you use a common dispatcher or bootstrap so this won't be a headache to implement) and use that in conjunction with other functions to produce a relative path.
Mike B
In my case it's the other way down. All requests are routed to /something/cms/index.php so setting ROOT_PATH from there results in /something/cms/, and I need to access the parent directory /something/. So I guess I'll just have to resort to some ugly string manipulation.
Tatu Ulmanen
A: 
$dir = dirname($file) . DIRECTORY_SEPARATOR;
Jordan Ryan Moore
A: 

Got it myself, it's a bit kludgy but it works:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

Tatu Ulmanen