Creating hit Counter



 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?

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();
        }
    }
}

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.

CodeIgniter provides a DBMS-independent query system, and mysql_* is deprecated anyways. It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use.

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. I have tried your code and I think its working the way I wanted. Thanks :) I guess I just now have to change the way of querying.
Creating hit Counter Creating hit Counter Reviewed by soksopheak on 2:09 AM Rating: 5

No comments:

Powered by Blogger.