Magento, Magento 2

How to Get Root Directory Path in Magento 2

How to Get Root Directory Path in Magento 2

In this tutorial, Today I will explain how to get the root directory path in Magento 2. If you need to root the directory path in your custom module then, you need to inject \Magento\Framework\Filesystem\DirectoryList class in your construct. So, Let’s check the below steps with output.

You may also like this :

1) Object Manager Method :

/**
 * Created By : Rohan Hapani
 */
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$directory = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
echo $rootPath  =  $directory->getRoot();
// Output : /var/www/html/m235

2) Dependency Injection Method :

/**
 * Created By : Rohan Hapani
 */

/**
 * @var \Magento\Framework\Filesystem\DirectoryList
 */
protected $dir;

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

public function getRootPath()
{
    return $this->dir->getRoot(); // Output : /var/www/html/m235 
}

Note : Avoid to use of object manager method directly.

However, If you want to get a media, var, pub, etc. directory path then, you can use the below codes to get the appropriate directory path.

Pub Directory Path in Magento 2 :

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

Media Directory Path in Magento 2 :

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

App Directory Path in Magento 2 :

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

Code Directory Path in Magento 2 :

$this->dir->getPath('code'); // Output : /var/www/html/m235/app/code

Design Directory Path in Magento 2 :

$this->dir->getPath('design'); // Output : /var/www/html/m235/app/design

etc Directory Path in Magento 2 :

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

lib internal Directory Path in Magento 2 :

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

log Directory Path in Magento 2 :

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

generated Directory Path in Magento 2 :

$this->dir->getPath('generated'); // Output: /var/www/html/m235/generated

view processed Directory Path in Magento 2 :

$this->dir->getPath('view_preprocessed'); // Output: /var/www/html/m235/var/view_preprocessed/pub/static

That’s it !!!

In other words, You can use the above code in your function based on your requirement. I also added the output of the code with a line of code.

I hope this blog is easy to understand how to get the root directory path in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged ,