Monday, October 3, 2011

Detect And Display A Visitor's I.P. Address


I've used derivations of this code to display visitor IP/hostname/User Agent information on my websites.


This is my PHP/JS without any MySQL backend:

<?php
Header("content-type: application/x-javascript");
date_default_timezone_set('CST6CDT');
$date = date(DATE_RFC822);
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$serverIP = $_SERVER['REMOTE_ADDR'];
$ref = $_SERVER['HTTP_REFERER'];
$useragent =  $_SERVER['HTTP_USER_AGENT'];
echo "document.write(\"We See You: <br><b>" . $serverIP . "<br>" . $hostname . "<br>" . $date . "</b>\")";
?>


I have named this script 'ip.php' and placed it on my web server (A Debian/Apache LAMP system in this case).
The following is a snippet from my index page into which I write the output of my 'ip.php' file:
<table>
<tr>
<td>
<script type="text/javascript" src="http://ADDRESS.EXAMPLE.COM/ip.php"></script>
</td>
</tr>
</table>




I have presented this deliberately spartan example that you may more easily work it into your own sites.

Notice the '$ref' and '$useragent' lines in the PHP do not appear in this output? You might choose to modify this code to display them to your visitors.









I have also built a MySQL database to do more detailed record keeping on my sites' traffic. If your site is hosted, your provider is probably doing this anyway and there are many packages out there which do much more elaborate recording/analysis of site traffic Webalizer comes to mind.




www.it-huntsville.com

No comments: