Tutorials

Article Content:how to build unique visitors counter with codeigniter

how to build unique visitors counter with codeigniter

how to build unique visitors counter with codeigniter.

Updated: download links added

In this tutorial, you will learn how to build unique visitor counter with Codeigniter.with simple and more effective ways. This way have also another feature. It will save more performance and more database query usage by using cookie 

First step I will suppose you will already have articles table like this

CREATE TABLE IF NOT EXISTS `articles` (
  `article_id` int(11) NOT NULL AUTO_INCREMENT,
  `article_cat_id` int(11) NOT NULL,
  `article_name` varchar(255) NOT NULL,
  `article_slug` varchar(255) NOT NULL,
  `article_body` text NOT NULL,
  `img_link` varchar(255) DEFAULT NULL,
  `article_state` tinyint(1) NOT NULL DEFAULT '0',
  `article_views` int(11) NOT NULL,
  `article_created` int(11) NOT NULL,
  PRIMARY KEY (`article_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;

If you don’t have article_views column then you should add this column. You will use this column to increase counter with every visit to your article page

The second step I will suppose you will already have function to show articles like this

class article extends CI_Controller
{
Function Show_article($slug){
// here you put your query to select the article 
//by slug or whatever by id
//then call the counter function  and pass the slug or the 
//id for the counter function
$this->add_count($slug);
}
 

// This is the counter function.. 
function add_count($slug)
{
// load cookie helper
    $this->load->helper('cookie');
// this line will return the cookie which has slug name
  $check_visitor = $this->input->cookie(urldecode($slug), FALSE);
// this line will return the visitor ip address
    $ip = $this->input->ip_address();
// if the visitor visit this article for first time then //
 //set new cookie and update article_views column  ..
//you might be notice we used slug for cookie name and ip 
//address for value to distinguish between articles  views
    if ($check_visitor == false) {
        $cookie = array(
            "name"   => urldecode($slug),
            "value"  => "$ip",
            "expire" =>  time() + 7200,
            "secure" => false
        );
        $this->input->set_cookie($cookie);
        $this->news->update_counter(urldecode($slug));
    }
}
}

The last step to update database counter in the article model

class article_model extends CI_Model {

function update_counter($slug) {
// return current article views 
    $this->db->where('article_slug', urldecode($slug));
    $this->db->select('article_views');
    $count = $this->db->get('articles')->row();
// then increase by one 
    $this->db->where('article_slug', urldecode($slug));
    $this->db->set('article_views', ($count->article_views + 1));
    $this->db->update('articles');
}
}

 

Download Link



  • Andy Suwito
    $this->db->where('entry_slug', urldecode($slug)); --> there is field entry_slug on your article table, is this correct ?? entry_views also, are yuu sure you give correct information?
    August 5, 2016
    Reply
    • admin
      info@webeasystep.com
      thanks Andy for your note and yes you are right,i fix this ,update code and table schema you are welcome :)
      August 5, 2016
      Reply
  • Nitin
    i am not getting what is variable $slug you have used is there any previous code there or is this incomplete code?
    August 23, 2016
    Reply
    • admin
      info@webeasystep.com
      Hi ,Nitin and you are welcome, Slug is to be as an alternative to using id as example : when you want to show and article you make URL like this : http:www.mysite.com/article/show/id but when using slug it will be like this http//:www.mysite.com/article/show/slug we use slug because it was more human readable and for search engine optimization,look at this article URL and see how it was. finally, i will accept your suggestion and i will make full code example available for download soon ,also i will make new tutorial for this thanks
      August 23, 2016
      Reply
  • Mauro
    Hello webeasystep, first of all thanks for your gift to the CodeIgniter community :) I'm creating a movie website using CodeIgniter framework and I would like to have a pageviews counter that tell me how many time a user see a movie page. I've written your code but it doesn't work. I kindly ask you an help. Below you can see what I've done... My database is structured in the following way: CREATE TABLE `film` ( `id` bigint(20) NOT NULL, `film_fullname` text, `film_nameurl` varchar(100) DEFAULT NULL, `views_count` int(11) NOT NULL, ) ENGINE=InnoDB DEFAULT CHARSET=latin1; So, I've updated my Film.php controller in the following way:
    November 7, 2016
    Reply
    • admin
      info@webeasystep.com
      Hello,Mauro you are welcome, i am so glad for your words,about your question can you give me the error or the issue in my code?,this will help me to fix it and also help other followers to skip this issue in the future. also 'doesn't work' is not a good problem description. i am waiting dude
      November 8, 2016
      Reply
      • Mauro
        mauro269@gmail.com
        Hello, thanks for your kind reply. I've seen right now that my comment has been cut by the blog comment system. I had detailed the issue. Anyway, I've found two issues. Issue #1 In the add_count() function of the controller, if I write: "value" => "$ip" the script is unable to store the ip address in the cookie. So I changed it in: "value" => $ip Issue #2 The "urldecode($slug)" doesn't give the possibility to the script to understand the value. I changed it directly in $slug in the entire code. Consider that my $slug saved in the database is -> my-url-name Thanks anyway. :)
        November 8, 2016
        Reply
  • Mauro
    Hello, I'm here again because I would like to store two kinds of visits data: 1) Total visits (and your script works like a charm); 2) Monthly visits. About the 2nd one, how can I do this? In particular, I would like to store visits from the 1st of the month to the last day of the same month and after that it should resets itself. Is it possible? thanks
    November 9, 2016
    Reply
    • admin
      info@webeasystep.com
      Hello, Mauro Sorry for delay,nowadays i prepare for marriage about you question,yes you can do it easily in three steps 1- Count visits normally like the script do 2- Create function to delete all visits counts records from tables. 2- Use cron job to automatically call delete function in a specific day in the month. you may need to read about cron job,see also my video about testing cron job locally. thanks
      November 9, 2016
      Reply
      • Mauro
        mauro269@gmail.com
        Uh, happy to hear that! My best wishes to you and your future wifi :D About your suggestion, thanks a lot!!! I'll let you know if I'll have success with it :D
        November 9, 2016
        Reply
  • jimmy
    i tried to follow the instructions but when i add the code into the page it mess everything up if you can help i will very much appreciate
    January 28, 2018
    Reply
  • Ade Adeyemi
    Thank you very much author you've done a good job. How do we add set counter to our view. Thank you
    August 27, 2020
    Reply

Leave a Reply

Your email address will not be published.


Notify me of followup comments via e-mail.
You can also Subscribe without commenting.