How to get absolute path of a file in Magento 2

How to get absolute path of a file in Magento 2

While building your custom extension, you will usually need path to your extensions files.

However sometimes you will need to get absolute path to Magento 2 root folder or maybe to media folder.

To directly access those files through your extension you can use Magento\Framework\App\Filesystem\DirectoryList class.

First you will need to inject DirectoryList class into your Magento 2 constructor:

public function __construct(\Magento\Framework\View\Element\Template\Context $context, \Magento\Framework\App\Filesystem\DirectoryList $directory_list, array $data = []) {
        parent::__construct($context, $data);
        $this->directory_list = $directory_list;  

After that you will have access to DirectoryList methods for retrieving various paths and it will be available to you through:



For getting your Magento 2 root folder you can use


For getting media folder you can use



Other possible uses are:

/* Get app folder */
/* Get configuration folder */
/* Get libraries or third-party components folder */
/* Get libraries/components that need to be accessible publicly through web-server folder */
/* Get public folder */
/* Get static folder */
/* Get var folder */
/* Get temporary files folder */
/* Get file system caching directory (if file system caching is used) */
/* Get logs of system messages and errors */
/* Get file system session directory (if file system session storage is used) */
/* Get directory for Setup application*/
/* Get Dependency injection related file directory */
/* Relative directory key for generated code*/
/* Temporary directory for uploading files by end-user */
/* Directory to store composer related files (config, cache etc.) in case if composer runs by Magento Application */
/* A suffix for temporary materialization directory where pre-processed files will be written (if necessary) */
/* Get template minification dir */

Share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInPin on Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *