Home  »  ArticlesGuidesTechnology   »   How to get the Current Working Directory in PHP

How to get the Current Working Directory in PHP

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.

Example:

echo getcwd();

The above example will output something similar to:

/path/to/folder

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.

Example:

require_once dirname(__FILE__) . '/folder/script.php';
echo dirname($_SERVER[PHP_SELF]);

Either of the above examples will output something similar to:

/path/to/folder

Using basename() PHP function

The basename function returns the trailing name component of path.

Example:

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

Conclusion

You have now learned three ways that you can get the current working directory in PHP.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.

Available under:
Articles, Guides, Technology