Reading list Switch to dark mode

    Get IP address of visitor in magento 2

    Updated 26 March 2024

    In this blog, you will see how to get the IP address of visitors in magento 2.

    <?php
    namespace Webkul\Module\Controller\DemoController;
    
    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;
        }
    }

    This will display the IP address of the user when this controller is hit.

    That’s it.

    You may also check the readymade plugin for Magento 2 GeoIP.

    Happy coding 🙂

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • thanhpv
    • Paul Dutta (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home