I am having problem with module approval. and magento connect validation report generates following message
Direct use of $_SERVER Superglobal detected
how can i use alternate for
$_SERVER['REMOTE_ADDR']
in Magento 2.
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityUsing an helper class extending the /Magento/Framework/App/Helper/AbstractHelper
class you can use the following:
$this->_remoteAddress
It is set in the AbstractHelper
class constructor:
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();
}
It comes from the /Magento/Framework/App/Helper/Context.php
class:
/**
* @return \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress
*/
public function getRemoteAddress()
{
return $this->_remoteAddress;
}
And it is an instance of \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;
}