Getting information about your visitors is interesting and sometimes useful for generating statistics, especially when you have a high traffic.
With PHP it’s easy to get your visitor’s IP, browser and operating system information, the page that referred him, the URL he visited and the time when he did it.
For this we use the following predefined variables:
$_SERVER['REMOTE_ADDR']
- gets the visitor's IP
Ex.: 192.168.0.1 (localhost IP)
$_SERVER['HTTP_USER_AGENT']
- the visitor's browser and operating system information.
Ex.: Mozilla/4.0 (compatible; MSIE 6.0; Windows 98)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Crazy Browser 1.0.5; .NET CLR)
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Hotbar 4.4.2.0)
Googlebot/2.1 (+http://www.googlebot.com/bot.html) - it means that Google crawls your website.
Mozilla/4.0 (compatible; MSIE 6.0... - this means the browser is Internet Explorer 6.0
Windows NT 5.1;... - this means the operating system is Microsoft Windows XP
Hotbar 4.4.2.0 - this is a browser extension (add-on)
$_SERVER['HTTP_ACCEPT_LANGUAGE']
- the visitor's operating system language.
Ex.: en, fr, hr, zh
You can find information about language codes at http://www.mondotimes.com/about/pop/languages.html.
$_SERVER['HTTP_REFERER']
the URL that referred the visitor to the current address.
Ex.: http://www.experts-exchange.com/Programming/Programming_Languages/Cplusplus/
/prog_ttrls_by_categ.php?id=4ℴ=date&sort;=desc&items;=10&start;=0
If the referer is internal (a page in your website, the referer will appear as in the second example. This way you can track your visitors closely.
$_SERVER['REQUEST_URI']
- the current URL the visitor has in its browser.
Ex.: /soft_artcls_list.php
/prj_proj_by_categ.php?id=3ℴ=date&sort;=desc&items;=10&start;=0
/
/ – means the root, the main page (index.php, index.html, default.asp…), for example www.geekpedia.com.
This is the code you’ll insert in your header that is probably included in all your pages.
mysql_query("insert into stats(vis_ip, vis_agent, vis_lang, vis_ref, vis_time, vis_url, vis_author, vis_country) values('".$_SERVER['REMOTE_ADDR']."', '".$_SERVER['HTTP_USER_AGENT']."', '".$_SERVER['HTTP_ACCEPT_LANGUAGE']."', '".$_SERVER['HTTP_REFERER']."', NOW(), '".$_SERVER['REQUEST_URI']."')");
And this is the query for the database:
CREATE TABLE `stats` (
`id_stat` bigint(5) NOT NULL auto_increment,
`vis_ip` varchar(15) NOT NULL default '',
`vis_agent` varchar(80) NOT NULL default '',
`vis_lang` char(2) NOT NULL default '',
`vis_ref` varchar(192) NOT NULL default '',
`vis_time` datetime NOT NULL default '0000-00-00 00:00:00',
`vis_url` varchar(96) NOT NULL default '',
PRIMARY KEY (`id_stat`)
) TYPE=MyISAM AUTO_INCREMENT=1720 ;
For more information, perhaps the visitor’s country you need an IP2Country database. This will probably pe covered in another tutorial 😉