How to Retrieve the Current Working Directory in PHP with getcwd()
This article explains the PHP getcwd() function for obtaining the absolute path of the current working directory, demonstrates 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 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 parameters; simply call it.
Example 1:
$currentDirectory = getcwd();
echo "当前工作目录是:" . $currentDirectory;Output:
当前工作目录是:C:/xampp/htdocsExample 2:
$directory = "/var/www/html";
chdir($directory);
$currentDirectory = getcwd();
echo "当前工作目录是:" . $currentDirectory;Output: 当前工作目录是:/var/www/html In the first example, we directly call getcwd() and store the returned absolute path in the $currentDirectory variable, then output it with echo.
In the second example, we first use chdir() to change the current working directory to the specified path "/var/www/html", then call getcwd() to retrieve the directory and store it in $currentDirectory, finally outputting it.
Note that the path returned by getcwd() is a server‑side path, which may differ from the client‑side request path. Ensure the working directory is what you expect when using the function.
Additionally, getcwd() may return false in special cases, such as when the script runs in an environment without a file system or when the current working directory has been deleted or renamed. It is advisable to check the return value for false to handle possible exceptions.
In summary, getcwd() is a very useful PHP function for obtaining the current working directory. After reading this article and the examples, you should have a deeper understanding of how to use it effectively in your PHP 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.
