Magento2 : Check it is frontend or backend?

Read More: blog.mageprince.com

With objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectManager->get('Magento\Framework\App\State');
echo $state->getAreaCode(); //frontend or adminhtml or webapi_rest

With Dependency Injection

protected $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function getArea()
{
    return $this->_state->getAreaCode();
}

Note: As per magento2 coding standards don't use object manager instance directly in files


People have answered the question already. I am just making it better.

const AREA_CODE = \Magento\Framework\App\Area::AREA_ADMINHTML;

private $_state;

public function __construct (
    \Magento\Framework\App\State $state
) {
    $this->_state = $state;
}

public function isAdmin()
{
    $areaCode = $this->_state->getAreaCode();
    return $areaCode == self::AREA_CODE;
}

Use below code

$objectmanager = \Magento\Framework\App\ObjectManager::getInstance();
$state =  $objectmanager->get('Magento\Framework\App\State');
if($state->getAreaCode() == 'frontend')
  //frontend
else
  //backend