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 '',
      `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.


8 Responses to “Get Site Visitor Information With PHP”

  • Chris Says:

    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.

  • Cody Taylor Says:

    Good Advice

  • ellisgl Says:

    Just wondering if you are going to expand this to get other information about the vistor?

  • Cody Taylor Says:

    I was thinking about writing some automated geolocation stuff. What would you like to see?

  • Ihab Khattab Says:

    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


  • Ihab Khattab Says:

    sorry I mean nasty stuff about other attacks not about output you already show a good stuff

    sorry again

  • Cody Taylor Says:

    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.

  • Getting Started (Part 2) « codeForBreakfast Says:

    […] 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 […]