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.

php Courses
php Courses
php Courses
How to Retrieve the Current Working Directory in PHP with getcwd()

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/htdocs

Example 2

$directory = "/var/www/html";
chdir($directory);
$currentDirectory = getcwd();
echo "Current working directory is: " . $currentDirectory;

Output example:

Current working directory is: /var/www/html

In 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPTutorialFilesystemgetcwdphp-functionsworking directory
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.