To store an IP address in Google Analytics, just add the following code to your pages, before the traditional Google Analytics code:
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP'];}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];} else {
$ip=$_SERVER['REMOTE_ADDR'];}
?>
In Google Analytics, click Admin, navigate to the wanted property, and in the "Property" column, click "Custom Definitions > Custom Dimensions". Click "New Custom Dimension", write "ip" as name and select "Session" as scope. Create the new dimmension. More info at: https://support.google.com/analytics/answer/2709829?hl=en&topic=2709827&ctx=topic.
Add this Google Analytics code to your website between <head> and </head>, only replacing the UA parameter:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-X', {
'custom_map': {'dimension1': 'ip'}
});
gtag('event', 'ip_address', {'ip': '<?=$ip;?>'});
</script>
To see the data:
1) Create a report in "Custom Reporting".
2) Select ip as first dimension. It will appear under "Custom Dimensions".
3) Select Sessions as metric.
If you cannot use PHP, you still can register your visitors' IP addresses via Javascript. However, you'll be depending on external code which, while functional now, could fail in the future. Use it under your own responsibility. The code is:
<script type="text/javascript" src="http://l2.io/ip.js?var=myip"></script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-X', {
'custom_map': {'dimension1': 'ip'}
});
gtag('event', 'ip_address', {'ip': myip});
</script>
Thanks to Matt Holovach for this solution!
1) Disable your current Google Analytics plug-in or delete it if you manually included it in the headers.php file.
2) Add the following code into your functions.php file:
<? function get_the_user_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return apply_filters( 'wpb_get_ip', $ip );
}
add_shortcode('show_ip', 'get_the_user_ip');
add_action('wp_head', 'add_google_analytics');
function add_google_analytics() { ?>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXXX-X"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-X', {
'custom_map': {'dimension1': 'ip'}
});
gtag('event', 'ip_address', {'ip': '<?php echo get_the_user_ip();?>'});
</script>
<?php } ?>
This script usually doesn't work in Analytics plugins for Wordpress, Shopify and other platforms, since these plugins usually don't run PHP scripts. If you're using Wordpress, remove your traditional Analytics plugin and replace it with a plugin that allows running PHP, such as Insert PHP.
i have implemented the code and let see how it works. Thanks for the PHP Code
I'm not seeing "visits" in the metrics dropdown. What would be a substitute?
"Sessions" is the new definition for "Visits". Kind regards.
Hi, I have tried on this but somehow it's not recording any IP address. Report is still "There is no data for this view." after few days. IP is seen on the code if I view the source of the page but I think it's not sending data to analytics. What could be the problem? What type of scope for the Custom Dimension? I set it to session or user but still the same. Does this still work on latest GA?
Hi Ryel. If you're using the latest GA (Universal Analytics), you have to: 1) create a new dimension manually inside Google Analytics, as explained here: https://support.google.com/analytics/answer/2709829?hl=en&topic=2709827&ctx=topic; 2) use the code I give under "Universal Analytics". You should change "dimension1" to the exact dimension number you just created.
Hi, Yes I did follow all the steps for new GA as I'm using new GA. Is "dimension1" you mean the custom dimension name too? I do not have other custom dimension just this one so it just dimension1 too right. What's correct type of scope for the custom dimension? Hit?
Can you pass me the resulting Javascript, as you see it in the source code? Let's see if I can help.
I have added the code to site and it is retrieving the IP. I have configured the Custom Dimension and has used the Universal Analytics code, but this is not showing any data on my report. Any ideas of what might have gone wrong?
Hi. The way Custom Reports are done is slightly different. I just updated this post. Please try to change your Custom Report and let me know if it works.
Thanks for the reply Daniel. But still I am not getting any data on my report. Adding the javascript and php codes below as used in website. Am I getting it wrong?
Hi. Unfortunately, these replies don't admit code with tags. Please send them to me via email, as well as the URL of the website. I'll wait for your answer. Kind regards.
Is this info still valid?
Yes, it's still valid.
hello there! nice post! i have a django site (Python) that i have tried to implement your code with. i have a question: will i see the IP addresses immediately or will it take some time to appear in my custom report in Google analytics?
It should take a couple of hours to appear. The only thing is that this code is for PHP. I'm not totally sure this will work on Python.
Thanks for this solution. I implemented it with Universal Analytics. It shows the visitors, but instead of IP address it shows =$ip;?>. Was this part of the code supposed to be replaced with something else?
Hi Raz. Can you please send an email to me, specifying the exact outcome you're getting? Tags are usually stripped from the comments.
I had tried this recently for www.bolasintelli.co.in. Working fine. It is one of the best tutorial to integrate and get IP address details
Great post. It's working! Really helpful.
Thanks for your comment! Have a great 2015!
I tried to implement it on my site. I built it in google sites Should it work ok as well? If do how much time it should take till I will see the data in the google analytics?
I've already talked to Michael about this issue. For all people reading this: you need to run PHP, you cannot use a platform like Google Sites.
This is great information. Thank you ! Like the other user, I must be doing something wrong as in Google analytics, I am getting counts, but the IP addy is listed as "=$ip;?>". Thoughts? Thanks
Hi Larry. Please send an email to me with the details of your URL. Kind Regards, Daniel.
why my report doesn't show anything? is it need time for process?
Hi Ariawan. Yes, you may need some extra time, maybe 2 hours. If you still don't see anything, please let me know via e-mail.
This is against Google's TOS (see section 7 about using personal information that google or a third party could use to identify an individual) http://www.google.co.uk/analytics/terms/us.html
I am getting counts but the IP add is listed as =$ip;?> Created a custom dimension IP with ID 5.Here's my code for IP capture: ga('send', 'pageview', { 'dimension5': '=$ip;?>' }); Please help
Please let me know the URL.
.Thank you ! Like the other user, must be doing something wrong as in Google universal analytics, the IP listed is as "=$ip;?>". If this a common problem? Would you be able to suggest some solutions that could help, without me having to submit some code? Kind regards Mark
Please let me know the URL.
Thanks for the code! Really useful!! I've got a question: Do you need to change "dimension1" to the name of the dimension (like IP), or is dimension1 also working? I'm working on the site: http://www.verzuimvitaal.nl . The code is right before the body tag.
Hi Anouk. You don't need to change "dimension1", it has to be like that. But you have to confirm that you're using the right code for your analytics type: universal or traditional. I'd rather insert the code in the header section.
Hi! I would like to use your code however I would need a clarification. I have google analytics universal and following your instructions, eventually I am supposed to replace ga('send', 'pageview'); in the Analytics main code. What do you mean exactly by Analytics main code? is it the google code part of my foot website? Thanks in advance.
Yes, that's it.
I attempted to use your code to collect IP address data, but the data is not being reported. Visiting IP addresses are accumulating, but the report only reads "=$ip;?>". I visited some other sites that are using your code, but each of them used your code differently. Any help with this problem would be greatly appreciated.
Please let me know your website's URL.
Daniel, Thank you very much for your article. I have used it effectively for a little while. My main use is to exclude people who have clicked on my PPC ads multiple times and it has helped tremendously for my clients. My only issue is it works for Desktop and Tablet devices, but not for mobile devices. This might be on me, because I don't utilize responsive design I utilize a tablet/ desktop site and a separate mobile site. Both sites utilize the same code above. But for some reason the mobile clicks aren't being tracked in my reports.
Hello Matt. It's very interesting. I think this may be related to some problem with Javascript. Can you let me know one of the mobile websites where you have included this code?
Hello Daniel, My web pages are .htm extension and I was wondering if the PHP code that goes before the traditional Google Analytics code will run as intended in a htm or html file.
Hello Sean. The PHP code will run only in servers with PHP. However, I've just updated this post with a Javascript alternative. Please check it out.
Hi Daniel great post thanks. Just a quick one, could this be used with Google Tag Manager? Thanks
Hi RK. It seems like you should create a new variable. I know very little about Google Tag Manager, so I'd suggest you to check this: http://www.simoahava.com/analytics/variable-guide-google-tag-manager/. Seems like, in this case, it would be easier to apply the Javascript solution.
Hello Daniel, Thank you for your posting. I followed your comments but IP dimension only shows =ip;?> Would you please check our website? and please let me know what is the problem. www.i-on.net
Hello Lia. The code has had a bug for a few days. Please just add the $ symbol before ip, inside the Google Analytics code, or copy and paste the code inside the post again.
Hi Daniel- This looks great! Unfortunately I am also only getting =$ip;?>. I'm sure it is probably something I'm doing, but any guidance would be helpful. I'm just testing on a single page for now: http://jmrl.org/li-wirelesstest.htm
Hi David. Seems like your webpage is not executing the PHP code. Can your server run PHP? If not, you can always try the Javascript solution I propose in this same post.
Hi Daniel- Again, thanks for taking the time to help out with this! My server does run php successfully for other pages, but I did as you suggested and ran the javascript. Same result! Does running the java still require the snippet for traditional or universal analytics? I'm using traditional. And does retrieving the java results involve the same customization? Thanks! David
Hello David. Can you try to do a simple "echo" in your test webpage, and see if it works? My first impression is that PHP is not running well on that webpage. Maybe you have to change the .htm extension.
David, Thanks for posting this. I am using square space and Universal Analytics. both the php and script get pasted into every page? my site is www.shieldcoart.com. Really appreciate it!
Only one script is necessary. PHP is preferable, but if you're site is not able to run PHP, then you can try with Javascript.
Hi Daniel, Thanks for this great post. I am able to integrate all this into my HTML webpage. My html page is parsing the php code successfully however, I cannot see any value for my custom dimension. Do you have any idea what should I be checking next?
I think you should be checking if you have actually created a custom dimension inside Google Analytics. If you need direct help, please let me know your website's address.
Hello Daniel; Great information. Working fine. It is one of the best tutorial to integrate and get IP address details! Thanks.
Hi Daniel, Thanks for this great post. I just followed your guide on my project. How can I see if it works? And I dont see any value in custom reporting. Would you please check our website? and please let me know what is the problem. comestoarra.koding.io/collaboration/jfx
Are you maybe using Universal Analytics?
Hi Daniel, Does this still work with the current google analytics (2016)? I had to update my site code from them so just curious. Can the php go anywhere in the page before the analytics code? Thanks.
Yes, it will work with current Google Analytics. Just use the Universal Analytics segment. And yes, the PHP can go anywhere before the Analytics code.
Hi Daniel, The 'dimension1': '=$ip;?>' code did not return the ip number under Drupal 7. However, the following code did the trick: 'dimension1': '' Thanks for the great tip.
Hi Daniel, I tried using the same to my Tumblr and I got the same =$ip;?> value in my IPs report. It seems to be a common prob for evry one.. Can you help out with exactly what needs to be fixed. thnx in advance:)
I don't think this will work in Tumblr. However, let me know the URL address so I can check it out.
Hi Daniel, here is website´s URL, if that helps. http://m.zamecnickapohotovost-sro.cz/ Thank you.
Hi. I don't see any Google Analytics code in your website. Please let me know.
Hi Daniel, I implemented it on Universal Analytics in Wordpress bud I dont see any IP, instead there is just this part of code: =$ip;?>. Do you have any ideal why is that? Thanks a lot Daniel.
I was able to get the code to work in Wordpress. First disable your current Google Analytics plug-in or delete it if you manually included it in the headers.php file. Then add the following code into your functions.php file. I needed to get this to work for a Wordpress client so I futzed with it for hours but I got it to work. So hopefully it will work for you. function get_the_user_ip() { if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return apply_filters( 'wpb_get_ip', $ip ); } add_shortcode('show_ip', 'get_the_user_ip'); add_action('wp_head', 'add_google_analytics'); function add_google_analytics() { ?>
Thanks Matt. I've just added your solution to the main post, hoping it helps people who are using Wordpress.
Hello, great post! Is this, what we are doing with codes, permitted by Google's policies ? Because no one would like to trick Google for getting the IP Addresses. Thanks
I think this is open to interpretation, depending on who you read. Google doesn't allow storing personal data. IP addresses may or not be considered personal data, depending on the lawyer you talk to. It's very open to interpretation, but I don't think Google will be prosecuting you for this. They have better things to do. I've seen worst things being stored in some Google Analytics accounts, such as phone numbers.
Hi, I am using the Wordpress solutions for Traditional Analytics that Matt provided and not sure if I am doing it correctly. Do I add the PHP to my functions and then the two other javascripts to the footer page above the
tag? THIS IN FUNCTIONS: function get_the_user_ip() { if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) { //check ip from share internet $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { //to check ip is pass from proxy $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return apply_filters( 'wpb_get_ip', $ip ); } add_shortcode('show_ip', 'get_the_user_ip'); add_action('wp_head', 'add_google_analytics'); function add_google_analytics() { ?> THESE IN FOOTER.PHP
The code, as written by Matt, is stand-alone. You shouldn't add anything before or after that code. First, you should remove the Google Analytics code in headers.php, and only insert Matt's code in the functions.php file.
IP addresses began accumulating - is there any way to time stamp these visits? Thanks!
If you're still interested, contact me via e-mail. Let me know URL of your website and give me access to your Google Analytics account, to fully understand the problem.
Michael, WORDPRESS UPDATE If you read this add the entire code including the script to the functions.php file. Obviously you will need to change the UA code on the analytics to match your code. FYI, You will probably have to remove the opening PHP tag and the closing tag ?> from the above code. Make sure you have FTP access to the files in case it doesn't work for you and temporarily bricks your wordpress account. That way you can manually edit the functions.php until it works properly. It shouldn't take trial and error but it might if you have a customized Wordpress functions.php file.
Thanks Man!
Hello Matt, I also tried your code posted, minus the PHP tags and got a Parse error:syntax error on my WP install. I also deactivated the GA plugin on WP. However when I use the other code above: if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLIENT_IP'];} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];} else { $ip=$_SERVER['REMOTE_ADDR'];} along with the javascript before the tag, it doesn't screw up my WP site: Time will tell if the IP is recorded or not. I'll report back, but it was the only code I could use that would not mess up my WP site.
John, I'm sorry that you had an issue. I was able to replicate my work on two different Wordpress sites so I was assuming that it would work for everyone. Sorry again for any issues this may have caused.
Hi, I implemented the code and started collecting the IP addresses on google analytics however, I have an issue. The IP addresses recorded appear to be not correct. In other words, I made a test. I asked a friend of mine to connect from Germany and google analytics properly recorded a village in Germany. At the same time, the IP address associated with this user does not correspond to be an IP from Germany, rather from France (I copied and paste the IP in few geolocation tools available on internet). Is there a bug in the code or did I do something wrong?
Hello Fabio. What I would do next is this: ask your friend to check some "What's my IP Address" tool, see what IP address comes out, and see if it matches with the IP address you're getting.
Hi Guys am not getting the list of ip's in GA for my website ,am using the following JS code any quick reply will be highly appreciable
Please send an email to me (check the email address under my picture), letting me know your website address.
Hi,I have followed the same steps as mentioned from INSTRUCTIONS FOR UNIVERSAL ANALYTICS. I implemented the code in my HTML,but I am not getting IP addresses. Please let me know where I am doing wrong. Thanks in advance.
Please send an email to me (check the email address under my picture), letting me know your website address.
Hi i am using google analytics recently i do no where i will get visitor ip address. I spend lot of time for this but still i did't get the answer please suggest me your feedback.
Hello Justin. Please let me know your website address.
Hello I have read all the comments to try to figure this out without any luck. I am adding the code per the instructions in the \"Site Wide Code\" tab of my godaddy website. Just like this: Only difference is I update my UA-XXXXXX number to be correct. After I click ok to save the code it seams it erases the top part of the code. When I go back into the \"Site Wide Code\" tab this is all that is left: I am not sure why it keeps erasing the first part of the code? Also, it does not show any data on my google analytics account when the code is like this. If I remove: { \'dimension1\': \'\' }); This portion it works again. Any advice? Thanks
Have you created the dimension inside Google Analytics? If you let me know your website address, maybe I can take a look at the code.
I tried to implement the code as per the above instructions. Instead of retrieving the visitor IP number it is retrieving this code string: =$ip;?> See screenshot here: https://www.dropbox.com/s/8wpf3z4wlydq0c5/Screenshot%202017-05-10%2017.16.34.png?dl=0 Any idea what I did wrong? Andrew
Hello Andrew. Seems like your website is not running on PHP. Maybe are you using a CMS or a platorm? If you let me know your website address, maybe I can help. Another option is using Javascript, as shown in the post.
Yes, I created the dimension in google analytics per the instructions above. Will this work in godaddy website builder site wide code tab? Thanks
What I understand is that the Godaddy\'s Website Builder is automatically erasing an essential part of the code. Maybe you should try to modify that file using a text editor, and then see if it works.
Hi, I used the javascript option. I am getting IPs like this in my GA reports 2605:e000:151e:813d:704c:44a0:10ca:20c5 I think this is version 6 format. Can you please guide?
Can you let me know your website?
Your \"INSTRUCTIONS FOR UNIVERSAL ANALYTICS\" are impossible to use. When I create a new report, Flat Table, and then click the leftmost popup next to Dimensions, if I type \"IP\" nothing appears and I cannot make IP stick in there manually. I can choose \"Sessons\" under Metrics, but again, I cannot choose \"IP\" under Dimensions. You need to examine this.
First, you need to create a custom dimension as explained here: https://support.google.com/analytics/answer/2709829?hl=en&topic=2709827&ctx=topic
Thanks for such easier explaination. It is working perfectly... :)
Iam trying to capture visitors IP on my website by google analytics report so that I can track the IPs if GA report successfully capture it.Help me how to achieve capturing visitor IPs and their search term from google.
This code will allow you to get the IP address, but it has become increasingly harder to get a search term since some years ago.
Thanks for great posting. I\'ve tired from fraud clicks via paid search. so, I need to find who clicks and block the ip address. If you add GTM case, it will be great but I might be solved if you give some advice. Please let me know I fully understand. 1) Add following script as below before GA code. 2) GTM connect GA without code. Currently, there are update in GA code as below. then which part need to revise? Thanks you in advance.
Thanks for the instructions, how do you recommend doing this using Google Tag Manager (ga tag is UA).
Hello Daniel and Matt. I am using wordpress solution. I implemented Matt\'s code and i created custom report in GA, everything as instructed. I do not have Google Analytics in my header.php but i implemented it via INSERT PHP plugin. But IP\'s are not showing up. I know the code is at least partly working because google analytics displays my activity under REAL-TIME section. What could be the issue? I would appreciate any help. Thank you
Is there something wrong that i did with my code? In google analytics, i\'ve followed the instructions for both universal and traditional ga, but the report only shows =$ip;?> in the column for IP. The parts for the codes i inputted is as shown below. Maybe the scripts are overwritting one another?
Can you tell me your website address?
Is the code not able to function for github pages? Maybe github pages has blocked IP tracking? i have tried both methods for ga, but the report in analytics just show =$ip;?> literally in the IP.
I don\'t think this will work in a GitHub webpage
I wanted to add some more information. I use this code regularly to track IP addresses of people trying to hit my clients online advertising activities so it is still important for me to capture IP addresses so I can keep Google somewhat honest or ban abusers from seeing my adds. In July Google Chorme is forcing people to switch to SSL or they will hit you with not secure nastygram (Here is a little more info http://bit.ly/2l27nbc. I wanted a free solution for my clients so I\'ve been using Cloudflare as a CDN and for free SSL. The problem is Cloudflare strips out the IP addresses. Add this code to your head however and the ip addresses will start coming through again. Sorry for the long post.
Daniel, I also wanted to give you a heads up that Google has come out with another new analytics code and your solution still works perfectly as I have implemented it with the new GA scripting. Have a great weekend and I wanted to thank you again for this great article I have used it at least 30 different times for different clients over the years. I have even added a Cloudflare solution which should help some people out as well.
Is this info still valid?