how to build unique visitors counter with codeigniter show to countor?
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 on the code here:
CREATE TABLE
IF NOT EXISTS `article` (
`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 - See more at:
// Function Show_article($slug){
// $this->add_count($slug);
// }
function
Show_article($slug){
$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);
//
echo $check_visitor;exit;
//
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 –like the code here:
//
----------------------------------------------hit countor--------------------
function
update_counter($slug) {
//return
current article views
$this->db->where('entry_slug',
urldecode($slug));
$this->db->select('entry_views');
$count
= $this->db->get('entry')->row();
$this->db->where('entry_slug',
urldecode($slug));
$this->db->set('entry_views',
($count->entry_views + 1));
$this->db->update('entry');
}
how to build unique visitors counter with codeigniter show to countor?
Reviewed by soksopheak
on
3:22 AM
Rating:
No comments: