如何修复 Magento 2 中的“检测到直接使用 $_SERVER Superglobal”
-
29-09-2020 - |
题
我在模块审批方面遇到问题。magento 连接验证报告生成以下消息
检测到直接使用 $_SERVER 超级全局
我怎样才能使用替代品
$_SERVER['REMOTE_ADDR']
在 Magento 2 中。
解决方案
使用辅助类扩展 /Magento/Framework/App/Helper/AbstractHelper
类你可以使用以下内容:
$this->_remoteAddress
它设置在 AbstractHelper
类构造函数:
public function __construct(Context $context)
{
$this->_moduleManager = $context->getModuleManager();
$this->_logger = $context->getLogger();
$this->_request = $context->getRequest();
$this->_urlBuilder = $context->getUrlBuilder();
$this->_httpHeader = $context->getHttpHeader();
$this->_eventManager = $context->getEventManager();
$this->_remoteAddress = $context->getRemoteAddress();
$this->_cacheConfig = $context->getCacheConfig();
$this->urlEncoder = $context->getUrlEncoder();
$this->urlDecoder = $context->getUrlDecoder();
$this->scopeConfig = $context->getScopeConfig();
}
它来自于 /Magento/Framework/App/Helper/Context.php
班级:
/**
* @return \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
public function getRemoteAddress()
{
return $this->_remoteAddress;
}
它是一个实例 \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
:
/**
* Retrieve Client Remote Address
*
* @param bool $ipToLong converting IP to long format
* @return string IPv4|long
*/
public function getRemoteAddress($ipToLong = false)
{
if ($this->remoteAddress === null) {
foreach ($this->alternativeHeaders as $var) {
if ($this->request->getServer($var, false)) {
$this->remoteAddress = $this->request->getServer($var);
break;
}
}
if (!$this->remoteAddress) {
$this->remoteAddress = $this->request->getServer('REMOTE_ADDR');
}
}
if (!$this->remoteAddress) {
return false;
}
return $ipToLong ? ip2long($this->remoteAddress) : $this->remoteAddress;
}