tags:

views:

88

answers:

2

I can create paths with no problem, but I want to know which of these 3 methods is the most rock solid and reliable and will work on the most servers.

Right now I am using method 1 in my script and some users are having path issues. I just want the method that will work on any version of php and almost any server config.

1.  <?php echo $_SERVER['DOCUMENT_ROOT']; ?>

2.  <?php echo getcwd(); ?>

3.  <?php echo dirname(__FILE__); ?>

Thank you so much for any expertise you can provide about this!

+8  A: 

dirname(__FILE__) will always work, regardless of platform or webserver. DOCUMENT_ROOT may work differently between server configurations (Apache vs IIS vs Lighttpd vs nginex). cwd shows the selected working directory which may or may not be correct (you can change it in the script). So I'd suggest dirname(__FILE__)

ircmaxell
+1 The first thing I add to a new project is `define('ROOT',realpath(dirname(__FILE__)).'/');`
Alec
+2  A: 
  • $_SERVER array holds user data and therefore can't be trusted is dependent on the platform (webserver).

  • The current working directory may depend on the entry point of the request. Consider this example (CLI):

    cd ~/mypath/mypath2
    php myscript.php
    cd ~/mypath
    php mypath/myscript.php
    
  • IMHO the securest solution is to use dirname(__FILE__) or __DIR__ (since PHP 5.3) as the file path will always be the same (relative to your projects structure).

Philippe Gerber
OK, it seems the consensus is that dirname(__FILE__) is th way to go. Thanks so much for helping!
mark
It's not correct to say that $_SERVER is all user generated. A lot of it is from the server side, not the client (e.g. the 'DOCUMENT_ROOT' value can be trusted).
Paul Dixon
you're right on this for the DOCUMENT_ROOT entry (and others of course). but still there are variables in the $_SERVER array that can be spoofed by the client/user. and in the context of the application that data is foreign and should not be trusted blindly.
Philippe Gerber