Page 1 of 1
View Counter
Posted: Wed Sep 08, 2010 5:52 pm
by Quazel
How would I make a view counter that:
1. Writes to a text file.
2. Adds 1 to the existing number and rewrites it in to the file.
3. Make a new line with a new number for each day.
I can use cron jobs but I prefer not to.
I want the text file to look something like this:
Re: View Counter
Posted: Wed Sep 08, 2010 6:43 pm
by Jonah Bron
Parts one and two are easy, all you need is inval(), file_get_contents(), and file_put_contents().
http://php.net/intval
http://php.net/file-get-contents
http://php.net/file-put-contents
Quazel wrote:I can use cron jobs but I prefer not to.
That's good, because you don't use cron to count hits anyway
I do not understand part three. Please clarify, and explain the purpose.
Re: View Counter
Posted: Wed Sep 08, 2010 7:54 pm
by Quazel
I do not understand part three. Please clarify, and explain the purpose.
I want a new line for each day.
Example:
The code writes 67 views to the file for 9/8 and there were no more views on 9/8 then some one views the page with this script on it on 9/9.
I want the file or a different script to be activate to make a new line and add 1.
Basically I want a script that would make a new line in the text file and write a 0 each day.
I hate referral links
Posted: Wed Sep 08, 2010 8:22 pm
by requinix
Compare the last modified time of the file to the current time: if the days don't match, write a newline before writing the new number.
Have you considered what would happen if two people tried to access whateveritis at the same time?
Re: View Counter
Posted: Wed Sep 08, 2010 8:45 pm
by Quazel
If that happens i'm off by 1 view what i'm using it for it only has to be close
Re: View Counter
Posted: Thu Sep 09, 2010 12:59 pm
by Jonah Bron
I see, you want separate lines for different days, each with the number of hits that day. You really shouldn't do that with a text file, because of the issues that arise when the file is accessed multiple times within the same moment (as tasairis stated), and because of performance.
Re: View Counter
Posted: Thu Sep 09, 2010 5:28 pm
by Quazel
Should I use sql then? how would I make the script figure out its a new day?
Re: View Counter
Posted: Thu Sep 09, 2010 6:11 pm
by Jonah Bron
Use a SQL query to check if there is a row for that day. If there is, add one to the `count` column (or whatever). If there isn't, make one and give `count` a value of 1.
Re: View Counter
Posted: Thu Sep 09, 2010 10:36 pm
by requinix
You can do it in one query if you make the date column be unique (eg, with a primary key).
Code: Select all
INSERT INTO table (date, count) VALUES (today's date, 1) ON DUPLICATE KEY UPDATE count = count + 1