Development

PHP getcwd() Function

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.
Captain Salem 1 min read
PHP getcwd() Function

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.

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.

Share
Comments
More from GeekBits

Join us at GeekBits

Join our members and get a currated list of awesome articles each month.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to GeekBits.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.