How to Retrieve the Current Working Directory in PHP with getcwd()
This guide explains PHP's getcwd() function for obtaining the absolute path of the current working directory, demonstrates usage with two code examples—including 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 or perform other operations. PHP provides the getcwd() function, which returns a string containing the absolute path of the current working directory. The function takes no arguments and can be called directly.
Example 1
$currentDirectory = getcwd();
echo "Current working directory is: " . $currentDirectory;Typical output:
Current working directory is: C:/xampp/htdocsExample 2
$directory = "/var/www/html";
chdir($directory);
$currentDirectory = getcwd();
echo "Current working directory is: " . $currentDirectory;Typical output: Current working directory is: /var/www/html In the first example the script simply calls getcwd() and stores the returned absolute path in the $currentDirectory variable, then prints it with echo.
In the second example the script first changes the working directory to a specific path ( /var/www/html) using chdir(), then calls getcwd() to retrieve the new directory and outputs it.
Important notes:
The path returned by getcwd() is the server‑side path, which may differ from the client‑requested URL.
If the script runs in an environment without a file system, or if the current directory has been deleted or renamed, getcwd() may return false. Always check the return value before using it.
In summary, getcwd() is a practical PHP function for obtaining the current working directory. Use it whenever you need the absolute path on the server, and remember to handle possible false returns for robust code.
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.
