Magento 2 – How to Get Base URL, Media URL, Current URL, Base Path, Media Path

In this blog, both methods are demonstrated, using Dependency Injection and using ObjectManager

Using Dependency Injection

Here is the sample code. It has been used in a block class but you may use it in any class you want. We will be using three classes:

\Magento\Store\Model\StoreManagerInterface\Magento\Framework\Filesystem\DirectoryList and \Magento\Framework\UrlInterface  
as follows:

You can see more functions in following classes:
/var/www/html/myproject/vendor/magento/module-store/Model/Store.php
/var/www/html/myproject/vendor/magento/framework/Url.php

Using ObjectManager

Well, this approach is never recommended as you know that using ObjectManager is never recommended in Magento 2. Find more about this here.

Though, we will see some of the methods to get work done: