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.
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:
1 2 3 |
$objctManager = \Magento\Framework\App\ObjectManager::getInstance(); $remote = $objctManager->get('Magento\Framework\HTTP\PhpEnvironment\RemoteAddress'); echo $remote->getRemoteAddress(); |
The implementation is simple, however, any doubts whatsoever, mention them in the Comments section below and I’d be happy to help 🙂
Do flash 5 stars for the post 😃
Thank you.
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 businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
6 Comments
hi, I am using this code but sometime its showing wrong ip address
Hey Ankit,
May be there must be an caching issue,
As the code works perfect on clean Magento.
how can i get the IP provided by ISP (The IP when we check on whatsmyip.com) ?
Hello Abdul,
If you use whatsmyip.com, you will get the same IP.
Thank you.
Hello i am magento fresher this code is where i past i don’t understand please help me
hello Akash,
Please place the code where you need the IP address,
Thank you.