1

Is there a way to find out the path of a user directory in php?

In MAC OS X I can use $_SERVER['DOCUMENT_ROOT'] to find out the path where the documents are being retrieved. This path is:

/Users/jmlopez/www

on my computer because I modified my httpd.conf file. I believe it was set to /Library/WebServer/Documents. In the server at my university it is set to:

/home/www/html

If I want to retrieve doc.html from a folder called testFolder I can simply use $_SERVER['DOCUMENT_ROOT'].'/testFolder/doc.html'. This works great but I cannot find out how to refer to documents located in the user pages.

Mac OS X

The user pages are set to be in:

/Users/USERNAME/Sites

Linux Server

The user pages in my university server are in

/home/www/users/USERNAME/www

Is there a way to get this path in php or do I have to analyze $_SERVER['SCRIPT_FILENAME']?

My Current Solution

My current solution to obtain the $fileRoot

$temp = explode("/", $_SERVER['SCRIPT_FILENAME']); 
if ( $temp[1] == "home" ) { //Linux
    if ( $temp[3] == "users") { $fileRoot = '/home/www/users/'.$temp[4].'/www';} 
    else { $fileRoot = '/home/www/html/'.$temp[4];} 
} elseif ($temp[1] == "Users" ) { //Mac
    if ( $temp[3] == "www" ) { $fileRoot = '/Users/'.$temp[2].'/www/'.$temp[4]; }
    else { $fileRoot = '/Users/'.$temp[2].'/Sites'; }
}

In this way if I'm working on a site, say http://localhost/someSite

then $fileRoot will point to:

/home/www/html/someSite 

in Linux.

/Users/jmlopez/www/someSite

in my mac.

Notice that $fileRoot = $_SERVER['DOCUMENT_ROOT'].'/someSite' works in both Mac and Linux.

If I'm working on my personal website say http://localhost/~jmlopez

then $fileRoot will point to:

/home/www/users/jmlopez/www

in Linux.

/Users/jmlopez/Sites

in my mac.

The question again is: Is there some way of obtaining this path without using the solution I have posted? Hopefully something simple.

4

1 回答 1

2

Apache 2.3.13 (also in 2.4.3) has a new feature that may be exactly what you need. I only read about it yesterday but have no had time to try it out. Obviously you'd need a very up-to-date apache as it's only been out a few weeks.

A new evnvironment variable is "CONTEXT_DOCUMENT_ROOT" which gets added to the $_SERVER variables. According to the change control, this will give you exactly what you need as was added for this purpose. Can't see any documentation other than the version control notes on it and 2.4 release notes

"Introduce new context_document_root and context_prefix which provide information about non-global URI-to-directory mappings (from e.g. mod_userdir or mod_alias) to scripts." Source: http://marc.info/?l=apache-cvs&m=130928191414740


Edit:

If you don;t have a recent version of Apache, then you probably have the best solution (check current file). You can also use

__DIR__

to get the directory of the file you're currently in too, which may be fractionally easier?

于 2012-08-27T01:35:03.623 回答