How to calculate page views in Codeigniter and limit count by IP address?
-
06-06-2021 - |
Domanda
I am looking to calculate how many times people have viewed my users profiles on my site.
I would like to keep a count in my database and to stop the count incrementing when a user refreshes the page. Limit by IP.
I understand that a cache of ip addresses would need to be created and emptied on a daily basis.
Is there any instruction on how to do this. Can anyone talk me through it?
Soluzione
- You can use
$this->input->ip_address()
to take the user's ip address in the controller - In the database you save the ip, the time the user first visited the site and a counter
- If the time is less than 24 hours, do not increment the counter.
- If the time is greater than 24 hours update the time for the ip and update the counter.
- Get the counter:
$this->db->select_sum("counter")->get("views_table");
and process the result.
Altri suggerimenti
Create databasetable:
id | page_id | ip_address | views
Read out ip address of user ($_SERVER['REMOTE_ADDR']
), check if ip-address is present in table for the current page, if so increment the views
column, otherwise create new record settings views
to one.
if views > $x
present them a neat message asking them to not be so curious.
wasn't that hard, was it? ;)
and for the part "stop the count incrementing when a user refreshes the page"; do you mean you want to only increment the count if the page view is not a refresh (someone pushing F5)? this is pretty much not possible, don't try it...
And for emptying the database, use a cronjob, or if you do not have access to it, a poormans cron (google for that)
- In the table where you store your users, add a column respresenting the view count.
- Each time your profile is visited you need to increment this value.
- Make a separate table as stated by giorgio and store the IP address but add a DATETIME column.
- Each time your profile is visited you need to check whether the IP address is present in that table for this profile: if it is then do not increment the view count; if it isn't then insert a new row with the IP address, your profile id and a datetime.
- Set up a cleanup job with cron once every day that determines the duration of tracking: remove all entries that are older 1 day, 2 days, a week - anything you want - this is how long the IP will be tracked. This means that when the same IP visits after x days the view count probably increment, unless it's still present in the database.