Current Location: Home> Latest Articles> Detailed Guide to Getting File Paths in PHP

Detailed Guide to Getting File Paths in PHP

M66 2025-10-30

Common Methods to Get File Paths in PHP

In PHP development, obtaining the absolute path of a file is a common requirement. Whether it's for loading configuration files, including templates, or locating log file paths, accurately determining the file or directory location is essential. This article introduces two commonly used methods to achieve this.

Using the __FILE__ Constant to Get the File Path

__FILE__ is a built-in PHP magic constant that returns the full path of the currently executing script file, including the file name. It allows you to quickly obtain the absolute path of the current file.

$filePath = __FILE__;

After running the above code, the $filePath variable will hold the complete path of the file on the server, for example:

/var/www/html/demo/index.php

Using the getcwd() Function to Get the Current Directory

The getcwd() function retrieves the current working directory (i.e., the directory where the script is executed). Unlike __FILE__, it returns the path of the directory, not the specific file.

$directory = getcwd();

Example output:

/var/www/html/demo

Difference Between __FILE__ and getcwd()

  • __FILE__ returns the full path of the current script file, including the file name.
  • getcwd() returns the path of the current working directory.
  • When a script is included (using include/require), __FILE__ returns the path of the included file, while getcwd() returns the directory of the main executing file.

Conclusion

Use the __FILE__ constant when you need the full path of a specific PHP file. Use the getcwd() function when you need to determine the current execution directory. Understanding the difference between the two helps you handle paths more flexibly in your projects.