0

A reliable way to get the actual (full) rootpath when the define is in a subdirectory? Consider:

E:\web\sites\name\index.php
E:\web\sites\name\res\defines.php
E:\web\sites\name\res\another.php
E:\web\sites\name\classes\class-example.php

Where E:\web\ is localhost and E:\web\sites\name is the intended root of the site.

An example path to define = E:\web\sites\name\data\feature\file.txt, in the manner of $file = ROOTPATH."\data\feature\file.txt";

The reason I don't use relative paths is because I want to pass the path in classes\class-example.php and also in res\another.php without using two constants for the same target.

So, in res\defines.php, what is the way to get the rootpath to point to E:\web\sites\name\? When the website is on a server, the same ROOTPATH should point to http://www.example.com/

Here's what I get when defines.php is in res\defines.php:

// Outputs: E:\web\sites\name\res
echo __DIR__;

// Outputs: E:\web\sites\name\res
echo realpath(__DIR__);

// Outputs: sites\name\res\another.php
echo $_SERVER['REQUEST_URI']

// Outputs: E:\web
echo $_SERVER['DOCUMENT_ROOT'];

// Outputs: sites\name\res\another.php
echo $_SERVER['SCRIPT_NAME'];

// Outputs: E:\web\sites\name\res\defines.php
echo __FILE__;

// Outputs: sites\name\res\another.php
echo $_SERVER['PHP_SELF'];
4

1 回答 1

0

The trick is to use: dirname(__DIR__) (PHP >= 5.3.0).

// Outputs: E:\web\sites\name
echo dirname(__DIR__);

Note that there are questions that are slightly like this, but none of those that I checked had the information about dirname(__DIR__); they all only mentioned dirname(__FILE__) which does not output the same thing as dirname(__DIR__) - the __FILE__ version outputs E:\web\sites\name\res

Hopefully this info helps others with a similar problem regarding subdirectories :)

It would be interesting to hear if someone has a solution for older PHP versions too, in case someone is using one...

于 2013-03-21T18:13:25.617 回答