Arrow

Using php to display visitor / user information such as their IP address

First published on July 4, 2006

There are domain names dedicated to displaying simple user information, such as your IP address. Some spam ads try and freak you out by saying that sites can tell what your IP address is. So what? Whenever you visit any website, you are usually sharing (unless you’re using a proxy server) lots of information about yourself, and you don’t have much of a choice.

Up until recently, I had no idea that if you have hosting with PHP (the vast majority of hosting offers PHP) you can show some fun information to your users about themselves. Here’s some simple info displaying your IP address, browser info, and the address that referred you to the page:

————————-

Display IP address:
127.0.0.1

More detailed host address:
localhost

Display browser info:
Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; [email protected])

Where you came from (if you clicked on a link to get here):

https://theblog.ca/?p=23

————————-

Here’s the code for what was just displayed above:

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$hostaddress = gethostbyaddr($ip);
$browser = $_SERVER['HTTP_USER_AGENT'];
$referred = $_SERVER['HTTP_REFERER']; // a quirky spelling mistake that stuck in php

print "<strong>Display IP address:</strong><br />\n";
print "$ip<br /><br />\n";
print "<strong>More detailed host address:</strong><br />\n";
print "$hostaddress<br /><br />\n";
print "<strong>Display browser info</strong>:<br />\n";
print "$browser<br /><br />\n";
print "<strong>Where you came from (if you clicked on a link to get here</strong>:<br />\n";
if ($referred == "") {
print "Page was directly requested";
}
else {
print "$referred";
}
?>

Note: to display php code in a WordPress post, try this plugin:
WordPress PHP Exec Plugin

Arrow

39 Responses to “Using php to display visitor / user information such as their IP address”


  1. Taj says:

    Thanks Peter,
    It was really helpful


  2. off-it says:

    Nice, thanks a heap for the code for this. Decided to look around the net to help freak out my site visitors ;) . Thanks to you. THis is all possible now :D

    Kindest regards
    Me


  3. Eric says:

    Great job, now i only need to know how to read other settings from the browser!


  4. kev says:

    nice one. thanks a lot! regards, k


  5. Eman says:

    I used the code above but this is what is returning..
    Yes my ISP has PHP installed .. Any ideas?

    –E

    Display IP address:
    \n"; print "$ip

    \n"; print "More detailed host address:
    \n"; print "$hostaddress

    \n"; print "Display browser info:
    \n"; print "$browser

    \n"; print "Where you came from (if you clicked on a link to get here:
    \n"; if ($referred == "") { print "Page was directly requested"; } else { print "$referred"; } ?>


  6. Eman says:

    Ya I am an I.D.I.O.T. I saved as .htm instead .php….

    Sorry for the kiddie post all … This issue drove me nutty for an hour..
    Sigh.. I need to sleep……..

    –E


  7. Charles Ujomu says:

    Nice one but can us it to check unwanted vistor in a particular site


  8. Peter says:

    If they have a constant IP address and you know what it is, you can block them with something like this in an .htaccess file (use multiple “deny” lines for multiple IP addresses):

    order allow,deny
    deny from 99.255.255.255
    allow from all


  9. Helen says:

    Hi Peter!
    Can you tell me how to report/post/save the data I collect from my visitors(specifically IP addy) to a file for future reference so I can later block certain IP’s from visiting/ordering from my website? Or can you point me to someplace I can find what I’m looking for?

    Thanks for the great info!

    Helen


  10. Peter says:

    Hi Helen, here’s some code I use on a very low-traffic website:

    <?php

    $filename = "ips.txt";
    $handle = fopen($filename, "a");
    fwrite($handle, $_SERVER['REMOTE_ADDR'] . "\n");
    fclose($handle);

    // Rest of code
    ?>

    Basically, it inserts a line into a text file with the visitor’s IP address whenever the page is accessed. Of course, you might want to add other information depending on what you’re looking for. Your server logs should also contain some good information on every single visit.


  11. Helen says:

    Hi Again Peter!
    Thanks so much for the very quick response and additional info! You mentioned the code you gave me "inserts a line into a text file" – I probably need to create that text file in the same directory as the page I’m using it on first….correct? Or does the script automatically create the text file via this snippet of the code: "$handle = fopen($filename, "a" "?? (sorry if that’s an obvious question – I am quite the novice when it comes to scripts;)

    My aim is to (hopefully;) prevent at least some of the many(far too many!) attempts to steal my services by paying for them with stolen CC’s and/or hacked PP accounts. I’m hoping that for at least some would-be theives – if they see their ip addy has been detected/recorded, maybe they won’t be quite so quick to attempt the theft(s) in the first place. I’m also open to suggestions for alternatives and/or additional preventitive measures if you happen to have any….thanks again Peter!

    Cheers!
    Helen


  12. Peter says:

    Hi Helen, yes, if your folder permissions are correct, that script will create the text file if it does not exist. If the file does exist, it simply adds to it.

    If you’re dealing with stolen CCs and hacked PP accounts, a more robust solution is more involved. Showing and recording people’s IPs alone might only act as a deterrent and not a real solution. The reason is that if you have a significant amount of visitors and only a simple list of IPs, you will have trouble matching IPs to visitors.

    Some web analytics solutions might be able to provide more detailed transactional information where you will be able to get an entry of information on each buyer. I am no expert here, so that’s about all I’ll say on that :D


  13. Dario says:

    Thank you peter for your great work.. please let me to know if i can use it in in my pages in tagged or window live space or Hi5 and how? i try in tagged but i couldnt put it (may be was my mistake because im just starter and not profisional ).thanks and have a nice day.


  14. Peter says:

    Hi Dario, unfortunately I don’t think you can add PHP code directly on those sites, although I could be wrong.


  15. smithveg-ergonomic says:

    How can i track the visitors’ country, and state?


  16. Peter says:

    To track country, you’ll need a database such as http://ip-to-country.webhosting.info/ or you’ll need to use JavaScript like with Google Analytics.


  17. SR22 Guy says:

    Peter,

    I would like to display something like this:

    "Hello Illinois visitor, thank you for visiting our site"

    Basically to show different state on each visit depending on where they are.

    Thanks,
    SR22 Guy


  18. Peter says:

    Hi SR22 Guy, you’ll definitely need some sort of external database, like the one linked in the comment above for countries. If anybody knows a good IP-state database, do let us know!


  19. Vasim Padhiyar says:

    hello all,
    is there any function in php or javascript that
    gives me the details of user’s local computer harddrive info also with all folder and files in that drive .


  20. John says:

    your a pretty clever guy mate…..some good stuff on here thanks


  21. Benjamin says:

    @Vasim Padhiyar:

    Are you freaking kidding? Next, are you going to ask if there’s a way to record people’s keypresses using php! F*** off!

    Seriously, though, if you want to do that, you’ll have to sucker somebody into installing a program.


  22. Benjamin says:

    Also, thanks for the $_SERVER variable info. I’m off to php.net right now to see what other cool $_SERVER variables are out there. :)


  23. What is Name ? says:

    Hello all ,
    Issue 1.
    is there any way to restrict user from entering some fix word using java script.

    Issue 2.
    How to Make Word Limit for textarea. Remember Word Limit not character limit.


  24. Barzini says:

    Thanks, works great. I modified it to insert it into a database and record it.


  25. Louis C. says:

    Peter,

    Nice code! I haven”t tried it yet, but I have bookmarked your page.

    I was wondering if you could help me figure out how to do something, of if it”s even possible.

    I am using Joomla! to manage a website. I have set up a plugin to redirect any unauthorized person trying to azccess the admin site to a custom 404 page. I plan on using this code to display the IP information etc. back to the offending user so they know they are being watched. This is nice, but what would be really awesome is if I could also have some PHP code in there to mail their information to my webmaster e-mail account so that I can put them on a block user”s list of some sort or track them on the web.

    I don”t need to know "everything" about them, but I would like to know who is trying to hack my site. =)

    Thanks!

    Louis


  26. Louis C. says:

    Dear Peter and Others,

    Well, I guess I answered my own questions and got some useful code together if any of you want to use it. This is the complete code for my "custom404.php" page that does the following:

    1) Gets user info (ip, hostname etc.)
    2) Displays a couple of messages along with that info back to the user who hits the page (you can customize this, of course)
    3) e-mails that info to the e-mail address of your choice! (IP and host name), – that was a bit of a trick to get working right – AND
    4) Redirects the user to another page of your choice after a certain designated period of time (in seconds).

    The notes in the code should be self-explanatory.

    This page won”t thwart a dedicated hacker, for sure, but it ought to be functional enough to scare off the average code-punk or plain old nosey person trying to lurk around the back end of your site.

    Enjoy!

    Louis

    Click here for the code


  27. AussieDave says:

    Hi Peter,

    You’ve got a great resource here, thank you!

    I’ve got a site that uses a user management system and people are abusing the registration form. All of these people seem to think that because they use a free email address they are anonymous…lol

    Your php code snippet has been implemented and it has reduced our form abuse to practically zero.

    Thanks again for making my life a little easier :-)

    Cheers

    AussieDave


  28. solow says:

    "Benjamin says:

    Are you freaking kidding? Next, are you going to ask if there’s a way to record people’s keypresses using php! F*** off!"

    Dude, there is. Using javascript you can record key presses using keycode.

    "Vasim Padhiyar says:

    hello all,
    is there any function in php or javascript that
    gives me the details of user’s local computer harddrive info also with all folder and files in that drive ."

    Yes there is. But is depends, what do you want to achieve? if you want to upload, it’s quite simple, else yes, you need to create some sort of add on, to browse trough your files. like a toolbar or sum.

    "Eric says:

    Great job, now i only need to know how to read other settings from the browser!"

    Interesting.
    Ok, some code for yah.

    $_SERVER['HTTP_USER_AGENT'] Get the users browser. Now this alone is boring don’t you think? So why not try adding this one:
    $browserInfo= get_browser(null, true);
    print_r($browserInfo);

    This’ll print the users browser, and what it is capable of. also, using this echo: echo $browserInfo['browser']; You won’t get this weird browser name, like, Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3. You’ll simply get: Firefox. Piece of cake. ?But using the print_r on that one’ll show you what it has.

    "What is Name ? says:

    Hello all ,
    Issue 1.
    is there any way to restrict user from entering some fix word using java script.

    Issue 2.
    How to Make Word Limit for textarea. Remember Word Limit not character limit."

    Interesting.

    Issue 1: Yes there is. But it’s quite disturbing to use. Each and every keyup, do a regular expression on these fixed words. best would be to use the php, asp, or whatever language it is you use to filter out these words. But this will be done after posting. so maybe fire up the javascript after pressing the submit button, so that the user doesn’t lose it’s text. also, please people, remember, filtering using javascript alone is NOT enough. Javascript can easily be turned off by the browser, and can be directly edited using tools such as firebug. Javascript is to enhance ‘Graphics’ and other pretty moving stuff, because people like pretty moving stuf… like woman love shiny stuff.

    Issue 2: Yes there is a way. You’ll be using javascript on this one, onsubmit of course. Now what you’ll do is split on spaces, this’ll give you the amount of words used. also, check if the last character is a space, because if it is, this doesn’t count as a word now does it ;) Then simply check, if necessary report back to the user and return false, else return true. But again, check this in your php as well.

    If my english sucks, sorry. I’m from Amsterdam The Netherlands :)


  29. THE MAN says:

    THANKS A LOT OF THIS!!!!!!!!!!!!!!!!!!!!!!!!


  30. Will Knot B. Revealed Snr. says:

    Thanks. :)


  31. muhu says:

    Hi,

    How can I make the server to write the visitors date and time in the ips.txt file for the visitors.

    I followed your instructions and that is writing the ip address of the visitors but how can I make the server to write the date and time of the visit. what would be the code for that.

    Thank you

    Mr Muhu

    Reply from Peter: Check the PHP documentation for date


  32. newphpblogger says:

    can I create an php script, not using ".php" as the file format but using "jpg" or other image’s name, so that I can insert it into my blogger?

    I ask this question is, some blogger administration only allow image to be inserted in blog. I want to insert the script in my blog.

    Reply from Peter: Not the way you describe it. If you have your own host, you could run PHP scripts on that server and embed the output elsewhere via iframes, images, or other output.


  33. Joseph McCullough says:

    Quick and easy, thanks a lot.


  34. NonSmoker says:

    Hi there.
    It is pretty practical, isn’t it?
    Do you also have a way to find out the visitors’ screen resolution?

    Thanks anyway,
    NonSmoker

    Reply from Peter: This can be done with JavaScript — there are probably a lot of example solutions if you Google for that.


  35. Roberto Lunelli says:

    The access can come from a proxy server and ip may be false.
    To get the IP’s better this way:

    <?php

    function getIp()
    {

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

    }

    return $ip;

    }

    ?>

    sorry my english sucks


  36. John says:

    Peter,
    Back in Oct. 2008 you replied to a user named Helen with the following script…

    Hi Helen, here’s some code I use on a very low-traffic website:

    <?php

    $filename = "ips.txt";
    $handle = fopen($filename, "a");
    fwrite($handle, $_SERVER['REMOTE_ADDR'] . "\n");
    fclose($handle);

    // Rest of code
    ?>

    Basically, it inserts a line into a text file with the visitor’s IP address whenever the page is accessed. Of course, you might want to add other information depending on what you’re looking for. Your server logs should also contain some good information on every single visit.

    The script works really good, but I have been trying to add an entry so that along with the IP Address it will also record the Date. So far I have been unsuccessful as I am somewhat new to PHP. Any help you can offer would be greatly appreciated.

    Thank you

    John

    Reply from Peter: You could replace the “fwrite” line with something like:

    $content = "[" . date( 'F j, Y, g:i a' ) . "] " . $_SERVER['REMOTE_ADDR'];
    fwrite($handle, $content . "\n");

    See the manual for the date function for date formatting possibilities.


  37. John says:

    Thanks for the help. Works great…


  38. Nada says:

    Hi Peter,

    I am recording the visitors ip address from your script. But that also recording my ip address too. How can I avoid recording my own ip address or some of the regular users ip address. Thanks

    Reply from Peter: You could set up an “if” statement to exclude your IP address; something like: if( $_SERVER["REMOTE_ADDR"] != "24.53.220.220" )


  39. Nada says:

    Thanks peter that works. That avoid my ip address being recorded. How can I avoid more than one ip addresses. I tried adding more ip address but that keep showing the error. Could you please let me know how to do that. Thanks

    Reply from Peter: The in_array function should help.

Speak your mind

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word