How to Get IP Address of Magento 2 Visitor

Note: As per EU’s GDPR law, make sure you have the visitors’ consent to detect their IP address, before implementing the below method.

“Customer data has become the key ingredient in providing a better customer experience,” said Tom Davis, Chief Marketing Officer at Forbes Media.

If you own a Magento 2 store, you must know the whereabouts of your store visitors! Keep an eye on who are your visitors and where do they come from.

This data is helpful to offer customized customer experience, validate data, prevent spam registrations, etc. For example, the visitor from India finds your store currency in INR and the visitor from the USA finds it in dollars. Hence, currency switching can be implemented based on the location data of the visitors.

Moreover, location data can be helpful in your marketing and advertising efforts. If you know the location of your majority of the visitors, you can tailor your marketing strategy accordingly. Make sure you’re allowing EU users to grant or deny permissions before collecting their data using Google’s Cookie Consent Mode V2.

Based on the language and choices of people coming from different parts of the world, you may want to offer content in various languages and of various types. For this, you first require to get IP address of Magento 2 visitor.

One of the smart ways to use the location data is to automatically fill out certain details in the forms such as country, city, zip code! Make it easy for the visitors to fill out the signup form of your Magento 2 store!

Method to Get IP Address of Magento 2 Visitor:

$objctManager = \Magento\Framework\App\ObjectManager::getInstance();
$remote = $objctManager->get('Magento\Framework\HTTP\PhpEnvironment\RemoteAddress');
echo $remote->getRemoteAddress();

With the above method, get IP address of Magento 2 visitor!

Thank you.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...