tags:

views:

94

answers:

4

I have a PHP file that I need it to detect it's directory it's in. In my case I want it to return C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\

I think that this is pretty straightforward but if there is something you don't understand just comment

+9  A: 

In PHP 5.3: __DIR__

In lower version: dirname(__FILE__)

Coronatus
+2  A: 

The magic-constant __FILE__ contains the full path to the file in which you write it.

The dirname function returns the path to the directory corresponding to a file.

So, in your case, to get the path to the directory containing your file, you can use :

echo dirname(__FILE__);
Pascal MARTIN
+1  A: 

In addition to the directory the file is in, you may find the directory that corresponds to the web server's / URI (http://www.example.com/ URL) useful. That's stored in $_SERVER['DOCUMENT_ROOT']

R. Bemrose
A: 

Yes, use dirname(__FILE__). (I think it's funny that it took until PHP 5.3 to finally get a __DIR__ magic constant to do the same thing...)

You might be tempted to use getcwd() because it appears to work but don't use it unless you know what you're doing - e.g., needing to get the pwd after a chdir() - because getcwd() only returns the current directory of the main referenced script in the URL. So, if you getcwd() in an include-file, it will show you the current directory of the file that included the file, not the include-file itself.

If your file is in /var/www/foo/subdir/ and you do something like:

   $dir = dirname(__FILE__) . DIRECTORY_SEPARATOR . '../'; 

then $dir will contain the string: "/var/www/foo/subdir/../". You can use realpath():

   $dir = realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR . '../');

to get $dir to contain: "/var/www/foo"

If you need to go relative to the document root you can use:

   dirname($_SERVER['SCRIPT_NAME']);

Don't rely on $_SERVER['DOCUMENT_ROOT'] in case it gets changed (someone changes it in a vhost after moving locations, or when your code goes live to another server, and so on). This is a perfect use for dirname(__FILE__) however; just put a constant pointing to dirname(__FILE__) in a file in your actual document root directory, if you need a constant linking to your document root, which you could then use instead of $_SERVER variables.

rkulla