5

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.

1 Answer 1

7

Using 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;
}
1
  • How can i get this in logo.phtml file direct. Sep 4, 2017 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.