php.getcwd()
CWD or current working directory refers to the directory or folder in a file system that is currently active or being accessed by a user or a program.
The current working directory is usually the directory where a user or program is located, and it is used as a reference point for locating other files or directories in the file system.
PHP being a versatile and popular programming language, it provides us with a function that allows us to get the current working directory in a simple method.
In this tutorial, we will learn how we can use the PHP built-in getcwd()
function to get the current working directory in our filesystem.
PHP getcwd() Function
As the name suggests, the getcwd()
function allows us to get the value of the current working directory under which the script is running.
The function syntax is as shown:
getcwd(): string|false
As you can see, the function does not accept any parameters.
It will then return the current working directory as a string on success and false
on failure.
Let us explore some basic examples.
Examples
Consider the following example demonstration of the getcwd()
function usage on various different operating systems.
PHP getcwd()
on Windows
The code is as shown:
<?php
echo getcwd() . "\n";
?>
The resulting output is as shown:
C:\Users\Salem
In this case, the function returns the full path current working directory.
PHP getcwd()
on Linux
On Unix, the output for the function is as shown:
<?php
echo getcwd() . "\n";
?>
Output:
/home/debian
Close.
Using this short tutorial, you learned how you can use the PHP getcwd()
function to get the path to the current working directory in PHP scripts.