Get Site Visitor Information With PHP
I wanted to do a few custom things with one of my site’s stats. PHP made this nice and simple with the $_SERVER array. When someone visits one of your scripts the $_SERVER array is automatically filled so as long as you know the keys then you can get all the information needed. These are the most useful items for identifying a visitor that I found in this using this array.
$_SERVER[‘REMOTE_ADDR’] gives you their ip address.
$_SERVER[‘HTTP_USER_AGENT’] is their user-agent (What browser they are using).
$_SERVER[‘HTTP_REFERER’] is where they came from.
$_SERVER[‘REQUEST_URI’] is the page they want to view.
This data is kinda useless unless you put it in a database so here’s a create table mySQL statement.
$sql = "CREATE TABLE visitors (
`visitor_id` mediumint(11) NOT NULL AUTO_INCREMENT,
`ip_address` VARCHAR(16) NOT NULL,
`user_agent` varchar(100) NOT NULL default '',
`time_of_visit` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`referrer` varchar(256) NOT NULL default '',
`target_url` VARCHAR(256) NOT NULL,
PRIMARY KEY (`visitor_id`)
);";
If you’d like to explore the $_SERVER array more there is very detailed info at the php web site.
June 6th, 2009 at
Note that $_SERVER[‘HTTP_REFERER’] will not be set if the browser did not pass this information along. If you are coding an error reporting level that includes notices it will show an error message if you access this value and it’s not set. So you’ll want to use something like isset() to check the array variable is set.
June 6th, 2009 at
Good Advice
June 6th, 2009 at
Just wondering if you are going to expand this to get other information about the vistor?
June 7th, 2009 at
I was thinking about writing some automated geolocation stuff. What would you like to see?
June 7th, 2009 at
Nice article
Please note that user can manipulate their user agents there is already Firefox add-one for that and a lot of other ways to other browsers
so you shouldn’t store it directly, you should consider if someone gonna make an SQL injection also you should consider escaping output to prevent XSS as you already outputting this and other nasty stuff
Thanks
June 7th, 2009 at
sorry I mean nasty stuff about other attacks not about output you already show a good stuff
sorry again
June 7th, 2009 at
Ahh. Good call about the sql injection. Didn’t even think about that. In production code I always make $_POST and $_GET safe but I don’t think I’ve ever made sure that the user agent is safe. I’m gonna have to go patch a few older projects.
September 15th, 2012 at
[…] way to do this. After I began on this process I did a quick search and found that someone called Cody Taylor had blogged about this exact issue a few years ago (which makes for a good sanity check) — and maybe there are some good cheap lessons for me […]