In PHP, getcwd() returns the current working directory of your script as a string. It answers the question: which folder are relative paths measured from right now?
When PHP resolves a relative path such as 'data.txt', it starts from the current working directory. getcwd() shows you that folder. It is different from __DIR__, which is the folder that contains the script file. getcwd() returns false if the folder cannot be determined.
Syntax
Call getcwd() with the values you need. Start with this line.
PHP
$cwd = getcwd();
Call
What it does
getcwd()
Returns the current working directory, for example /var/www/html. It takes no arguments.
basename(getcwd())
Returns just the name of the current folder.
getcwd() . '/data.txt'
Builds a full path to a file inside the current folder.
getcwd() and __DIR__ are often the same, but not always. The working directory can change with chdir(), and it can be different when a script is started from another folder on the command line.
Library declarations
PHP
getcwd(): string|false
Parameters
Parameter
Description
—
This function takes no parameters.
Return Value
Return Value
Description
string|false
Returns the current working directory as a string on success. Returns false on failure. On some Unix systems it can fail if a parent folder has no read or search permission.
PHP Examples
Example 1 — getcwd() Follows chdir()
We start in the script folder, move into a demo folder, and watch getcwd() change while __DIR__ stays the same.
We enter the demo folder, so the working directory is now demo-getcwd-file.
file_put_contents('note. txt', ...) uses a relative path, so the file is created in the working directory.
getcwd() . DIRECTORY_SEPARATOR . 'note.txt' builds the full path using the correct slash for the system.
file_exists() confirms the file is at that exact place, and then we clean up.
Frequently Asked Questions
It returns the current working directory as a string. This is the folder PHP uses to resolve relative paths such as 'data.txt'.
__DIR__ is the folder that contains the file being run, and it never changes. getcwd() is the working directory, which can be changed with chdir() or can depend on how the script was started.
Yes, but it is rare. It can happen on some Unix systems when a parent folder is not readable. Check with === false before using the result.
Normally no, except for the root folder. Add DIRECTORY_SEPARATOR yourself when you join a file name to it.
The working directory depends on how PHP was started. A web server often uses the script's folder or its own folder, while the CLI uses the folder where you typed the command. Use __DIR__ for predictable paths.