There are several ways to get the current working directory in PHP depending on what you are working on. Generally, you want to use these methods to programmatically find out which directory a running script is in.
Current Working Directory Using the getcwd() PHP Function
This PHP function returns the current working folder on success and false on failure. The function is called with no parameters.
On some Unix variants, getcwd() will return false if any one of the parent directories does not have the readable or search mode set, even if the current directory does.
The above example will output something similar to:
Working Directory Using dirname() PHP Function
dirname function returns a parent directory’s path or depending on the parameters you can define how far up the parent path you want to return.
To get the current directory using dirname() you need to add the PHP predefined FILE constant or PHP_SELF.
require_once dirname(__FILE__) . '/folder/script.php'; echo dirname($_SERVER[PHP_SELF]);
Either of the above examples will output something similar to:
Using basename() PHP function
The basename function returns the trailing name component of path.
echo "1) ".basename("/path/to/folder", ".d").PHP_EOL; echo "2) ".basename("/path/to").PHP_EOL; echo "3) ".basename("/path/").PHP_EOL;
The above examples will output something similar to:
1) folder 2) to 3) path
You have now learned three ways that you can get the current working directory in PHP.