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.
__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.phpThe 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/demoUse 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.