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:
1 2 3 4 5 |
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList'); echo $rootPath = $directory->getRoot(); |
1 2 3 4 5 6 7 8 9 10 |
protected $dir; public function __construct(\Magento\Framework\Filesystem\DirectoryList $dir) { $this->dir = $dir; } public function getRootDirectory() { return $this->dir->getRoot(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
$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.
Any doubts about the solution can be mentioned in the Comments section below. I’d be glad to help you out.
Do share the solution with the Magento Community via social media.
Thank you.
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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
$this->_dir->getRoot();
Does this code work anywhere in phtml?
Is there no need to declare any other code?
Hey Dennis you have to declare like this as mentioned in blog :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$directory = $objectManager->get(‘\Magento\Framework\Filesystem\DirectoryList’);
Great~
Thank You Dennis!