I would like to create a simple web statistics javascript code ( analytics )
but wondering whats the correct way to include referer ?
I think somehow need to implement javascript escape(document.referrer) with php inside track.php
This is what i have so far :
script on remote site:
<script type="text/javascript" src="http://www.mydomain.com/track.php"></script>
local track.php:
<?php
$str = 'document.write(\'<img src="http://www.mydomain.com/tracking.php?id="/>\');';
echo $str;
?>
local tracking.php
<?php
header("content-type:image/gif");
$ip = $_SERVER["REMOTE_ADDR"];
$browser = $_SERVER['HTTP_USER_AGENT'];
//$referer = ????
///etc...
// save results to db ...
3 Answers 3
You want to build a list of all params, for example...
var params = {
resolution: screen.width + ',' + screen.height
};
...then you need to serialise them to GET params...
var serialisedGetParams = [];
for (var param in params) {
if ( ! params.hasOwnProperty(param)) {
continue;
}
serialisedGetParams.push(param + '=' + encodeURIComponent(params[param]));
}
serialisedGetParams = serialisedGetParams.join('&');
...then make a request...
(new Image).src = 'http://yourdomain.com/track.php?' + serialisedGetParams;
The params you send should be stuff only JavaScript can get, such as resolution etc. Sending them via the GET params of an image allows you to bypass Same Origin Policy.
Additionally, the image request can get information such as the IP, Referrer, etc. Examine the $_SERVER super global for a wealth of information about the request.
3 Comments
document.referrer property can be spoofed more easily than the $_SERVER['HTTP_REFERER'] superglobal.Have you considered using Google Analytics? (or any other free product). It's very likely going to be better and faster than anything you could write. The only downside is that you're selling your soul to Google ..
If you want to show your boss fancy pictures, this is the way to go :P
Comments
I would make an AJAX call and pass to your PHP pages the inforamtion you need to save directly taken from javascript.
Like location.href, user agent and other stuff
$_SERVER['HTTP_REFERER'].