Backend Development 4 min read

Using PHP getcwd() to Retrieve the Current Working Directory

This article explains the PHP getcwd() function, demonstrates how to retrieve the current working directory with example code, discusses changing directories with chdir(), highlights potential false returns, and provides best practices for using getcwd() in server-side scripts.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP getcwd() to Retrieve the Current Working Directory

When writing PHP code, you often need to know the current working directory to correctly reference files or perform other operations. PHP provides the convenient getcwd() function to obtain the current working directory.

The getcwd() function returns a string containing the absolute path of the current working directory. It takes no arguments and can be called directly.

Example 1:

$currentDirectory = getcwd();
echo "当前工作目录是:" . $currentDirectory;

Output:

当前工作目录是:C:/xampp/htdocs

Example 2:

$directory = "/var/www/html";
chdir($directory);
$currentDirectory = getcwd();
echo "当前工作目录是:" . $currentDirectory;

Output:

当前工作目录是:/var/www/html

In the first example, getcwd() is called directly and its result is stored in $currentDirectory , then echoed.

In the second example, chdir() changes the working directory to "/var/www/html" before calling getcwd() and echoing the result.

Note that getcwd() returns the server‑side path, which may differ from the client request path, so ensure the working directory is as expected.

Also, getcwd() may return false in special cases, such as when the script runs in an environment without a filesystem or the current directory has been deleted or renamed; therefore, check for false before using the result.

In summary, getcwd() is a very useful PHP function for obtaining the current working directory. Use it to get accurate results in your scripts.

BackendPHPFilesystemgetcwdchdirworking 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

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