How to Retrieve the Current Working Directory in PHP with getcwd()
This guide explains the PHP getcwd() function, shows two practical code examples—one using getcwd() directly and another after changing directories with chdir()—and highlights important considerations such as server‑side paths and handling false returns.
When writing PHP code you often need to know the current working directory to reference files correctly. PHP provides the built‑in getcwd() function, which returns the absolute path of the current working directory as a string and takes no arguments.
Example 1
$currentDirectory = getcwd();
echo "Current working directory is: " . $currentDirectory;Output example:
Current working directory is: C:/xampp/htdocsExample 2
$directory = "/var/www/html";
chdir($directory);
$currentDirectory = getcwd();
echo "Current working directory is: " . $currentDirectory;Output example:
Current working directory is: /var/www/htmlIn the first example the function is called directly and its return value is stored in $currentDirectory before being printed. In the second example chdir() first changes the working directory to /var/www/html, after which getcwd() is called to retrieve the new path.
Note that getcwd() returns the server‑side path, which may differ from the client‑side request path, so you should ensure the directory is the one you expect. Additionally, getcwd() can return false in special situations such as when the script runs in an environment without a filesystem or when the current directory has been deleted or renamed; therefore it is good practice to check the return value before using it.
In summary, getcwd() is a practical PHP function for obtaining the current working directory, and the examples above demonstrate its typical usage.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
