PHP getcwd() Function

What is PHP getcwd() Function?

If you want to get the full directory path of your current script, call getcwd() function. getcwd is short for “Get Current Working directory”.

Syntax:

getcwd()

Parameters:

The Function has no parameter.

Return Values:

The function returns-

  • The directory path where the current script is running – on success
  • FALSE – on failure.

Examples:

Example 1: Displaying current directory path-

<?php
echo "Your Current Working Directory Path is: " . getcwd();
?>

Output:

Your Current Working Directory is: D:\xampp\htdocs\php

Example 2: Displaying current directory path after changing directory-

<?php
echo "Your Current Working Directory Path is: " . getcwd() . "<br />";
chdir("file");
echo "Your new Current Working Directory Path is: " . getcwd();
?>

Output:

Your Current Working Directory is: D:\xampp\htdocs\php
Your new Current Working Directory is: D:\xampp\htdocs\php\file

Explanation:

With chdir() function, we changed the directory to “file”. So this is the latest path of the current directory.

Notes on getcwd() Function:

  • On some Unix operating system if readable mode or search mode of any of the parent directories is not set, the getcwd() doesn’t work and returns FALSE.

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Summary: PHP getcwd() Function

Depending on the output of the getcwd() function, you can do the other file and directory related operations like listing directory entries, constructing file path. This is a built-in PHP directory function.

Reference:

https://www.php.net/manual/en/function.getcwd.php