How to Get Root Directory Path in Magento 2

Are you a Magento developer working on building extensions?

If yes, then you will have to get root directory path in Magento 2.

You will need access to data stored in the root folder which can be obtained using the directory path.

Hence, implement the below solution to get a directory path in Magento 2.

Method to Get Root Directory Path in Magento 2:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');

echo $rootPath  =  $directory->getRoot();

or

protected $dir;

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

public function getRootDirectory()
{
    return $this->dir->getRoot();
}

Get other directory paths like:

$this->_dir->getRoot();

$this->_dir->getPath('media');

$this->_dir->getPath('pub');

$this->_dir->getPath('static');

$this->_dir->getPath('var');

$this->_dir->getPath('app');

$this->_dir->getPath('etc');

$this->_dir->getPath('lib_internal');

$this->_dir->getPath('lib_web');

$this->_dir->getPath('tmp');

$this->_dir->getPath('cache');

$this->_dir->getPath('log');

$this->_dir->getPath('session');

$this->_dir->getPath('setup');

$this->_dir->getPath('di');

$this->_dir->getPath('upload');

$this->_dir->getPath('generation');

$this->_dir->getPath('view_preprocessed');

$this->_dir->getPath('composer_home');

$this->_dir->getPath('html');

That’s it.

Do share the solution with the Magento Community via social media.

Thank you.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...