I need a way to track unique visitors and the number of repeat visitors to my site. I will most likely need to keep this info in a flat(txt) file, and then have a report that displays these statistics. Could someone help with the code to do this?
@jrthor2authorJul 18.2005 — #Unfortunately, none yet. I was just asked if this can be done, which I'm sure it can be, but I was looking for some help since I'm not that proficient in php yet.
@bokehJul 19.2005 — #It can be done. You would need to use cookies to flag a returning user and if they delete their cookies they would appear as a new user.
@bokehJul 20.2005 — #Database would be better than flat file. Nevertheless I have thrown together the following code. It logs the number of users and the number of pages each user views.
Put this code at the very top of each page you want to monitor: [code=php]<?php $file = 'users.php'; $fp = fopen($file, 'a+'); $tries = 5; while($tries > 0){ $locked = flock($fp, LOCK_EX); if(!$locked){ sleep(1); $tries--; }else{ $tries = 0; } } if($locked) { fseek($fp, 0); while (!feof($fp)) { $fgets = fgets($fp); if(!empty($fgets)){ list($key, $value) = split(' ', trim($fgets)); $tmp[$key] = $value; } } if(!isset($_COOKIE['user'])){ $count = count($tmp) + 1; setcookie ('user', $count, time()+10000000, '/', '', 0); $tmp[$count] = '1'; }else{ $tmp[$_COOKIE['user']]++; setcookie ('user', $_COOKIE['user'], time()+10000000, '/', '', 0);
Put the following code by itself in a file (called, for example, reader.php). [code=php]<?php $file = 'users.php'; $tmp = file($file); print'<table class="table" border="1" cellspacing="0" cellpadding="8"> <caption>Table 1:<br>User Data</caption> <thead> <tr> <th>User</th><th>Views</th> </tr> </thead> <tbody> '; foreach($tmp as $value){ list($user, $views) = split(' ', trim($value)); print "<tr><td>user $user</td> <td>$views</td></tr>n"; } print '</tbody> </table>'; ?>[/code]
Put reader in the same directory as your web files. After a few pages have been accessed run reader.php to see the output.
My script actually creates the flat file but on some systems you may either need to create it or change its permissions. I tested this on a windows machine and this was not necessary but on Linux, who knows!