Search code examples
phpdirectoryseparator

Extract main directory name of php application


I would like to get only the application name of my project, For example my application name(Directory Name) is : MERP The path of the application is: C:/xampp/htdocs/MERP So I need to get only the name MERP.

There is another way storing application name inside a config file using define syntax and include in all the files, but my scenario is stuck with this step only.


Solution

  • For Php files under a directory within and under your document root:

    You could try:

    strtok(str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', __FILE__), DIRECTORY_SEPARATOR);
    

    However, this is still brittle. And I would advice against it, preferring a setup/bootstrap file with constant declaration, and a possible place for common functions.

    Php allows for a common file to be applied before your scripts, see the auto_prepend_file directive. This might be useful if you want to go beyond a few constants, and saves the require lines from individual files.

    If you only wish for a handful of constants, consider environmental variables.