Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method for creating absolute path in PHP? (See 3 methods listed inside)

Tags:

path

php

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!

like image 832
mark Avatar asked May 23 '10 19:05

mark


People also ask

What is __ file __ in PHP?

The __FILE__ constant returns full path and name of the PHP file that's being executed. If used inside an include, the name of the included file is returned.

What is dirname (__ file __) in PHP?

dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap. php resides. (Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__) .)

What is absolute and relative path in PHP?

Absolute and Relative PathsAn absolute path refers to a file on the Internet using its full URL, e.g. "http://www.uvsc.edu/disted/php/webct/itr/index.php" A relative path assumes that the file is on the current server, e.g. "php/webct/itr/index. php".


2 Answers

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__)

like image 63
ircmaxell Avatar answered Nov 03 '22 00:11

ircmaxell


  • $_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).

like image 27
Philippe Gerber Avatar answered Nov 02 '22 23:11

Philippe Gerber