1

In magento 1 it

$user_agent = Mage::helper('core/http')->getHttpUserAgent();
$remote_ip = Mage::helper('core/http')->getRemoteAddr();

Are there any similar features in magento 2 ?

0

2 Answers 2

8

You can use this below code :

protected $httpHeader;
protected $remoteIp;

public function __construct(
    \Magento\Framework\HTTP\Header $httpHeader,
    \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteIp
)
{
    $this->httpHeader = $httpHeader;
    $this->remoteIp = $remoteIp;
}
public function execute(){
    $userAgent = $this->httpHeader->getHttpUserAgent();
    $remote_ip = $this->remoteIp->getRemoteAddress();
}
0

Try below code:

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\HTTP\PhpEnvironment\RemoteAddress;

class DemoClass extends Action {
 private $remoteAddress;

 public function __construct(
     Context $context,
     RemoteAddress $remoteAddress
 ) {
    $this->remoteAddress = $remoteAddress;
    parent::__construct($context);
}

public function execute()
{
    $ip = $this->remoteAddress->getRemoteAddress();
    echo "Visitor's IP = ".$ip;
}

}

Your Answer

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

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