This article shows how we can check if current URL and frontend URl are secure (https) or not in Magento 2.
Below is a block class of my custom module (Chapagain_HelloWorld). I have injected object of StoreManagerInterface in the constructor of my module’s block class.
app/code/Chapagain/HelloWorld/Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_storeManager;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []
)
{
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
/**
* Check if frontend URL is secure
*
* @return boolean
*/
public function isFrontUrlSecure()
{
return $this->_storeManager->getStore()->isFrontUrlSecure();
}
/**
* Check if current requested URL is secure
*
* @return boolean
*/
public function isCurrentlySecure()
{
return $this->_storeManager->getStore()->isCurrentlySecure();
}
}
?>
See more functions in vendor/magento/module-store/Model/Store.php.
Now, we can use the above function in our template (.phtml) file.
var_dump($block->isFrontUrlSecure()) . '<br />';
var_dump($block->isCurrentlySecure()) . '<br />';
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
var_dump($storeManager->getStore()->isFrontUrlSecure());
var_dump($storeManager->getStore()->isCurrentlySecure());
Hope this helps. Thanks.