W3docs

How to get root directory in yii2

In Yii2, you can use the following code to get the root directory:

In Yii2, you can use the following code to get the root directory:

Example of getting root directory in yii2

$root = dirname(__DIR__);

The __DIR__ constant returns the directory of the current PHP script (e.g., web), and the dirname() function returns its parent directory, which corresponds to the project root.

Alternatively, you can use Yii's built-in path alias to get the root directory:

Example of using Yii's built-in path alias to get the root directory

$root = \Yii::getAlias('@app');

This returns the path to the application root directory as defined in the configuration. Note that in the basic template, @app points to the project root, while in the advanced template it typically points to the specific web application directory (e.g., frontend or backend). For consistent path handling, ensure the returned string does not contain a trailing slash by using rtrim($root, DIRECTORY_SEPARATOR) if necessary.