Get the Current Directory
Sometimes you write a function in PHP that needs to know where in the directory hierarchy the code is being called from, to correctly access other files, such as those to be read, written or included. If the same function appears throughout your site, you can’t ‘hard code’ the location, because it changes from one web page to another, if you site spans more than one directory.
PHP, of course, provides a simple solution:
$dir=getcwd();
So, for example, using the above code in a script on your page at mysite.com/widgets/goodstuff.php might return the value:
home/mysite/public_html/widgets
The only cautionary note when using this function, is to remember that it will return the working directory of the calling script, rather than included script, if it is used within an include. So, if your
$dir=getcwd();
is in a file at home/mysite/public_html/includes
And you include it in a script running at home/mysite/public_html/widgets
It will set the $dir variable to that second path, not the path where the included file resides.
Filed under: Functions | Leave a Comment
No Responses Yet to “Get the Current Directory”