tags:

views:

71

answers:

2

Hello.

I am trying to create a simple Hit Counter using Kohana3 and PHP. But when I load a page with it, it counts as 1-3 times (normally, the first hit 3, then 2, then 1).

The code I'm using:

$game = ORM::factory('game')
    ->find_by_slug($slug);

if(!$game->loaded())
{
    $this->request->redirect('/',404);
}

$game->times_played++;
$game->save();  

An example page: http://www.plugb.com/game/qrossfire EDIT: Number of times played is below description.

How can I solve this?

Thank you.

EDIT:

I've found some requests like this:

/game/qrossfire
Agent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)

/game/stickmen-swat
Agent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)

/game/qrossfire
Agent: MetaURI API +metauri.com
A: 

Not sure if this is the issue, but try adding an exit statement after the redirect to make sure it stops there.

if(!$game->loaded())
{
    $this->request->redirect('/',404);
    exit;
}
Brad F Jacobs
Tried this and nothing changed. I'm pretty sure that Kohana's redirect already does that.
Gabriel Bianconi
Hmm, it could be the .htaccess file that is causing an issue. You may try and do a hash of the user_agent and the ip check via session, if that hash has been entered for that page, then omit it. There are probably better ways to do this, but yea.
Brad F Jacobs
+1  A: 

Have a look at the requests your browser is making, and check that it's not somehow making more than one to that page. You might have some other files in the page (e.g. images etc) matching that route.

You can check both the client side (with addons like Firebug) and the serverside (by watching the webserver access log)

Lethargy
I've found some requests like this: /game/qrossfireAgent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php) /game/stickmen-swatAgent: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php) /game/qrossfireAgent: MetaURI API +metauri.com
Gabriel Bianconi
If you're developing on your live site those are probably what is causing the counter to go up inexplicably; other clients requesting the page.This suggests your code works, it's just a matter of filtering out the requests you wish to ignore.
Lethargy
Gabriel Bianconi
The last is, actually, !stristr(Request::$user_agent, 'facebook')
Gabriel Bianconi