views:

216

answers:

2

In PHP what is the difference between

getcwd()
dirname(__FILE__)

They both return the same result when I echo from CLI

echo getcwd()."\n";
echo dirname(__FILE__)."\n";

Returns:

/home/user/Desktop/testing/
/home/user/Desktop/testing/

Which is the best one to use? Does it matter? What to the more advanced PHP developers prefer?

A: 
Daniel A. White
Nope, this time it just echos /home/user/Desktop/testing/testing2 twice
Urda
OK, so let me be sure I got this...dirname(__FILE__) will *always* produce the location of the file in use. While getcwd will return the current working dir for the PHP process running (such as my command line script.)So assuming this, if I use a include("path/to/some/file/from/chdir/"); it should be able to find the referenced file?
Urda
+3  A: 

__FILE__ is a magic constant containing the full path to the file you are executing. If you are inside an include, its path will be the contents of __FILE__.

So with this setup:

./foo.php

<?php
echo getcwd() ,"\n";
echo dirname(__FILE__),"\n" ;
echo '-------',"\n";
include 'bar/bar.php';

./bar/bar.php

<?php
echo getcwd(),"\n";
echo dirname(__FILE__),"\n";

You get this output (Windows / Zend Studio Debugger):

C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
-------
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random
C:\Users\me\Zend\workspaces\DefaultWorkspace7\random\bar

Appearantly, getcwd returns the directory where the file you started executing resided, while dirname(__FILE__) is file-dependant.

The Guy Of Doom
Perfect example is perfect! Thank you!
Urda