How to Get Current Directory in PHP

09/08/2021

Contents

In this article, you will learn how to get current directory in PHP.

Using the getcwd() function

You can get the current directory in PHP using the getcwd() function. The getcwd() function in PHP returns the current working directory of the script, which is the directory the script was executed from.

Here’s an example:

<?php
  $current_directory = getcwd();
  echo "The current directory is: " . $current_directory;
?>

This will print the absolute path of the current working directory.

Using the __DIR__ magic constant

You can also use the __DIR__ magic constant to get the current directory in PHP. The __DIR__ constant returns the directory of the file it is used in.

Here’s an example:

<?php
  $current_directory = __DIR__;
  echo "The current directory is: " . $current_directory;
?>

This will print the absolute path of the directory that contains the file where the __DIR__ constant is used.

Using the dirname() function

Another way to get the current directory in PHP is by using the dirname() function in combination with the __FILE__ magic constant. The __FILE__ constant contains the full path and filename of the file it is used in, while the dirname() function returns the directory portion of a file path.

Here’s an example:

<?php
  $current_directory = dirname(__FILE__);
  echo "The current directory is: " . $current_directory;
?>

This will print the absolute path of the directory that contains the file where the __FILE__ constant is used.

Using the $_SERVER superglobal array

another way to get the current directory in PHP is to use the $_SERVER superglobal array. The $_SERVER array contains information about the web server and the current request, including the script name and the path to the current directory.

Here’s an example:

<?php
  $current_directory = dirname($_SERVER['SCRIPT_FILENAME']);
  echo "The current directory is: " . $current_directory;
?>

This will print the absolute path of the directory that contains the currently executing script.