How to get the root directory path in Magento 2?
How to get the root directory path in Magento 2?

How to get the root directory path in Magento 2?

You can use \Magento\Framework\Filesystem\DirectoryList class to get a directory path.

You can get directory path of root, media, pub, var etc…

Here is an example of how you can get root directory path.

By ObjectManager:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
echo $rootPath  =  $directory->getRoot();

By dependency Injection:

protected $_dir;

public function __construct(
    ...
    \Magento\Framework\Filesystem\DirectoryList $dir,
    ...        
) {
    ...
    $this->_dir = $dir;
    ...
}

Now you can get root directory path by $this->_dir->getRoot();

Here is the list of possible directory path of Magento 2

$this->_dir->getRoot(); // Output: /var/www/html/myproject

$this->_dir->getPath('media'); // Output: /var/www/html/myproject/pub/media

$this->_dir->getPath('pub'); // Output: /var/www/html/myproject/pub

$this->_dir->getPath('static'); // Output: /var/www/html/myproject/pub/static

$this->_dir->getPath('var'); // Output: /var/www/html/myproject/var

$this->_dir->getPath('app'); // Output: /var/www/html/myproject/app

$this->_dir->getPath('etc'); // Output: /var/www/html/myproject/app/etc

$this->_dir->getPath('lib_internal'); // Output: /var/www/html/myproject/lib/internal

$this->_dir->getPath('lib_web'); // Output: /var/www/html/myproject/lib/web

$this->_dir->getPath('tmp'); // Output: /var/www/html/myproject/var/tmp

$this->_dir->getPath('cache'); // Output: /var/www/html/myproject/var/cache

$this->_dir->getPath('log'); // Output: /var/www/html/myproject/var/log

$this->_dir->getPath('session'); // Output: /var/www/html/myproject/var/session

$this->_dir->getPath('setup'); // Output: /var/www/html/myproject/setup/src

$this->_dir->getPath('di'); // Output: /var/www/html/myproject/var/di

$this->_dir->getPath('upload'); // Output: /var/www/html/myproject/pub/media/upload

$this->_dir->getPath('generation'); // Output: /var/www/html/myproject/var/generation

$this->_dir->getPath('view_preprocessed'); // Output: /var/www/html/myproject/var/view_preprocessed

$this->_dir->getPath('composer_home'); // Output: /var/www/html/myproject/var/composer_home

$this->_dir->getPath('html'); // Output: /var/www/html/myproject/var/view_preprocessed/html

NOTE: you can also use echo BP; to get absolute path of Magento.

NOTE: Don’t use object manager directly. Read this for more info:https://magento.stackexchange.com/questions/117098/magento-2-to-use-or-not-to-use-the-objectmanager-directly