black_belt
black_belt

Reputation: 6799

Creating hit Counter

I am trying to create a hit counter for my website and I have developed the following code for it. I have included the following code only in Codeigniter's main controller for my home page.

At first I thought the code was working fine but I just found that if I don't keep on browsing the pages then again go to the home page it doesn't update the data. I mean for example: If I go to my homepage for the first time then it updates the data, but after 10 seconds if I refresh the page it does't update the data. But if I keep refreshing it for 10 seconds then it works.

So could you please tell me how to get it update the data without having to keep on browsing the pages or refreshing the home page?

Thanks :)

function __construct() {

    parent::__construct();

    // Visitor Counter
    if (!$this->session->userdata('timeout')) {

        $out = time() + 10; // I will change it to $out = time() + 60*60; later 
        $this->session->set_userdata('timeout', $out);
        mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat+1 
              WHERE id = '1'");
    } else {
        $timeout_time = $this->session->userdata('timeout');
        if (time() > $timeout_time) {

            $this->session->set_userdata(array('timeout' => ''));
            $this->session->sess_destroy();
        }
    }
}

edit

What I am trying to achieve is when an user visits the webpage for the first time, I want to update my database. Within 10 seconds (for example purpose), if the visitor again visits the home page, the database will not be updated. But after 10 seconds if he again visits the home page, I want to update my database.

Thanks :)

Upvotes: 0

Views: 3323

Answers (1)

Dan Grossman
Dan Grossman

Reputation: 52372

Your code says "if there is no timeout in the session, update the count". You want it to say "if there is no timeout in the session, or there is but it's old, update the count".

function __construct() {

    parent::__construct();

    // Visitor Counter
    if (!$this->session->userdata('timeout') || $this->session->userdata('timeout') < time()) {
        $this->session->set_userdata('timeout', time() + 10);
        mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat + 1 WHERE id = 1");
    }

}   

I'm not a CodeIgniter user, so I am assuming that you used its session facilities correctly; I just used them the same way.

Upvotes: 2

Related Questions