How to get root directory in yii2

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

$root = dirname(dirname(__DIR__));

The __DIR__ constant returns the directory of the current PHP script, and the dirname() function is used to get the parent directory of the current script. By calling dirname() twice, we are able to get the root directory.

Watch a course Learn object oriented PHP

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

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

This will return the path to the application root directory, which is defined as an alias in the configuration file.