在 Magento 2 中检查 url 是否安全 https、ssl 的 2 个步骤

  • 第 1 步:声明Example_HelloWorld
  • .phtml步骤2:在模板文件中声明函数

第 1 步:声明Mageplaza_HelloWorld

您将使用 module 的块类,然后可能在模块的块类的构造函数中Example_HelloWorld注入 的对象。StoreManagerInterface

app/code/Mageplaza/HelloWorld/Block/HelloWorld.php

<?php
namespace Example\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();
    }    
}
?>

您可以在 中看到更多功能vendor/magento/module-store/Model/Store.php

.phtml步骤2:在模板文件中声明函数

.phtml在模板文件中运行以下函数

var_dump($block->isFrontUrlSecure()) . '<br />';
var_dump($block->isCurrentlySecure()) . '<br />';