How to Get a Visitor's IP Address in Google Analytics

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'];}
?>

Then, follow these instructions depending on if you use Universal Analytics or the traditional Google Analytics.

INSTRUCTIONS FOR UNIVERSAL ANALYTICS

Create a new dimension as explained here, set "IP" as name and "Session" as scope. Then use this Google Analytics code, replacing the UA parameter:

<script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXX-X', 'auto');
    ga('send', 'pageview', {
      'dimension1':  '<?=$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.

INSTRUCTIONS FOR TRADITIONAL ANALYTICS

Add this code to your webpages before </body>:

<script type='text/javascript'>
 _gaq.push(['_setCustomVar', 1, 'IP', '<?=$ip;?>', 1]);
</script> 

To see the data:
1) Create a report in "Custom Reporting".
2) Select Custom Variable (Value 01) as first dimension.
3) Select all the web metrics you want to see (visits, pageviews, time on site, etc.),

Once the first IP addresses are retrieved by the code, you can see the IP addresses of all your visitors, and then combine them with traditional Google Analytics metrics.

HOW TO USE JAVASCRIPT TO GET AN IP ADDRESS

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>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXX-X', 'auto');
    ga('send', 'pageview', {
      'dimension1':  myip
    });
</script>

INSTRUCTIONS FOR WORDPRESS

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>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXXXXX-1', 'auto');
    ga('send', 'pageview', {
      'dimension1':  '<?=get_the_user_ip();?>'
    });
</script>
<? } ?>

DOES THIS SCRIPT FOR GETTING IP ADDRESSES WORK IN WORDPRESS?

This script usually does't work in Analytics plugins for Wordpress, since Wordpress 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.

Contribute with a comment comment92 Comments
  1. 2017-05-16 Arif

    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?

    • 2017-05-20 Daniel Piñero

      Can you let me know your website?

    2017-05-11 Dennis

    Yes, I created the dimension in google analytics per the instructions above. Will this work in godaddy website builder site wide code tab? Thanks

    • 2017-05-11 Daniel Piñero

      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.

    2017-05-10 Andrew

    I tried to implement the code as per the above instructions. Instead of retrieving the visitor IP number it is retrieving this code string: 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

    • 2017-05-11 Daniel Piñero

      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.

    2017-05-10 Dennis

    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

    • 2017-05-11 Daniel Piñero

      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.

    2017-02-28 Justin

    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.

    • 2017-02-28 Daniel Piñero

      Hello Justin. Please let me know your website address.

    2016-07-25 Soujanya

    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.

    • 2016-07-25 Daniel Piñero

      Please send an email to me (check the email address under my picture), letting me know your website address.

    2016-07-25 Prem

    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

    • 2016-07-25 Daniel Piñero

      Please send an email to me (check the email address under my picture), letting me know your website address.

    2016-07-17 Fabio

    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?

    • 2016-07-17 Daniel Piñero

      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.

    2016-06-13 Matt Holovach

    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.

    2016-06-05 John

    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.

    2016-05-06 Vinayak Mudgal

    Thanks Man!

    2016-03-19 Matt Holovach

    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 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.

    2016-03-18 Van

    IP addresses began accumulating - is there any way to time stamp these visits? Thanks!

    • 2016-03-18 Daniel Piñero

      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.

    2016-03-18 Michael

    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: THESE IN FOOTER.PHP

    • 2016-03-18 Daniel Piñero

      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.

    2016-02-22 Akhil

    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

    • 2016-02-22 Daniel Piñero

      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.

    2016-02-21 Matt Holovach

    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() { ?>

    • 2016-02-21 Daniel Piñero

      Thanks Matt. I've just added your solution to the main post, hoping it helps people who are using Wordpress.

    2016-02-21 Tomas

    Hi Daniel, I implemented it on Universal Analytics in Wordpress bud I dont see any IP, instead there is just this part of code: . Do you have any ideal why is that? Thanks a lot Daniel.

    2016-02-21 Tomas

    Hi Daniel, here is website´s URL, if that helps. http://m.zamecnickapohotovost-sro.cz/ Thank you.

    • 2016-02-21 Daniel Piñero

      Hi. I don't see any Google Analytics code in your website. Please let me know.

    2016-02-21 Rockinfreakshow

    Hi Daniel, I tried using the same to my Tumblr and I got the same 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:)

    • 2016-02-21 Daniel Piñero

      I don't think this will work in Tumblr. However, let me know the URL address so I can check it out.

    2016-01-26 Alan W

    Hi Daniel, The 'dimension1': '' code did not return the ip number under Drupal 7. However, the following code did the trick: 'dimension1': '' Thanks for the great tip.

    2016-01-26 Don

    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.

    • 2016-01-26 Daniel Piñero

      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.

    2015-12-24 Achmad Rizal Muttaqin

    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

    • 2015-12-24 Daniel Piñero

      Are you maybe using Universal Analytics?

    2015-12-24 Leo Asafrana

    Hello Daniel; Great information. Working fine. It is one of the best tutorial to integrate and get IP address details! Thanks.

    2015-12-17 Rahul

    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?

    • 2015-12-17 Daniel Piñero

      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.

    2015-10-20 Neil

    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!

    • 2015-10-20 Daniel Piñero

      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.

    2015-09-20 David

    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

    • 2015-09-20 Daniel Piñero

      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.

    2015-09-13 David

    Hi Daniel- This looks great! Unfortunately I am also only getting . 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

    • 2015-09-13 Daniel Piñero

      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.

    2015-08-28 Lia

    Hello Daniel, Thank you for your posting. I followed your comments but IP dimension only shows Would you please check our website? and please let me know what is the problem. www.i-on.net

    • 2015-09-04 Daniel Piñero

      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.

    2015-08-28 RK

    Hi Daniel great post thanks. Just a quick one, could this be used with Google Tag Manager? Thanks

    • 2015-08-28 Daniel Piñero

      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.

    2015-08-19 Sean Zee

    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.

    • 2015-08-20 Daniel Piñero

      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.

    2015-07-27 Matt Holovach

    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.

    • 2015-07-27 Daniel Piñero

      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?

    2015-07-24 Baumgart

    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 "". 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.

    • 2015-07-24 Daniel Piñero

      Please let me know your website's URL.

    2015-07-24 Fabio

    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.

    • 2015-07-24 Daniel Piñero

      Yes, that's it.

    2015-06-21 Anouk Kolkman

    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.

    • 2015-06-21 Daniel Piñero

      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.

    2015-06-03 Mark

    .Thank you ! Like the other user, must be doing something wrong as in Google universal analytics, the IP listed is as "". 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

    • 2015-06-03 Daniel Piñero

      Please let me know the URL.

    2015-06-03 Ori Olapade

    I am getting counts but the IP add is listed as Created a custom dimension IP with ID 5.Here's my code for IP capture: ga('send', 'pageview', { 'dimension5': '' }); Please help

    • 2015-06-03 Daniel Piñero

      Please let me know the URL.

    2015-04-17 Matt

    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

    2015-03-13 Ariawan

    why my report doesn't show anything? is it need time for process?

    • 2015-03-13 Daniel Piñero

      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.

    2015-03-06 Larry

    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 "". Thoughts? Thanks

    • 2015-03-06 Daniel Piñero

      Hi Larry. Please send an email to me with the details of your URL. Kind Regards, Daniel.

    2015-02-20 Michael

    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?

    • 2015-02-21 Daniel Piñero

      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.

    2014-12-31 Gopi

    Great post. It's working! Really helpful.

    • 2014-12-31 Daniel Piñero

      Thanks for your comment! Have a great 2015!

    2014-12-22 Bolas Intelli

    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

    2014-12-19 Raz

    Thanks for this solution. I implemented it with Universal Analytics. It shows the visitors, but instead of IP address it shows . Was this part of the code supposed to be replaced with something else?

    • 2014-12-19 Daniel Piñero

      Hi Raz. Can you please send an email to me, specifying the exact outcome you're getting? Tags are usually stripped from the comments.

    2014-11-21 toufic zaarour

    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?

    • 2014-11-21 Daniel Piñero

      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.

    2014-11-12 Lokal

    Is this info still valid?

    • 2014-11-12 Daniel Piñero

      Yes, it's still valid.

    2014-09-04 RR Nair

    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?

    • 2014-09-04 Daniel Piñero

      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.

    2014-08-05 RR Nair

    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?

    • 2014-08-05 Daniel Piñero

      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.

    2014-07-28 Ryel

    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?

    • 2014-07-28 Daniel Piñero

      Can you pass me the resulting Javascript, as you see it in the source code? Let's see if I can help.

    2014-07-28 Ryel

    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?

    • 2014-07-28 Daniel Piñero

      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.

    2014-07-20 Denny

    I'm not seeing "visits" in the metrics dropdown. What would be a substitute?

    • 2014-07-20 Daniel Piñero

      "Sessions" is the new definition for "Visits". Kind regards.

    2014-03-07 Subu

    i have implemented the code and let see how it works. Thanks for the PHP Code

mode_editContribute with a comment

menu
menu