How to get root directory path in a phtml magento 2?
Class \Magento\Framework\Filesystem\DirectoryList is used to get path like root, media, var etc
This will get root directory of your project like this
/var/www/html/myproject
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;
...
}
Get other directory paths like
$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 should never use \Magento\Framework\App\ObjectManager::getInstance()
It defeats the purpose of dependency injection.
You can use magento 2 default variable to get absolute path of Magento directory
echo BP;
You have to use ROOT for get root directory
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$fileSystem = $objectManager->get('Magento\Framework\Filesystem');
$mediaPath = $fileSystem->getDirectoryRead(\Magento\Framework\App\Filesystem\DirectoryList::ROOT)->getAbsolutePath()