How do I run a script (ie, $viewcount += 1;) when a session starts in PHP? I'm trying to make a view counter script for my website which currently works, assuming I include('view_counter.php') in every page to add something to my text file of views. Unfortunately, people can reload the page and so add up the view count really quickly. What I'd like to do is add to the view count every time somebody opens a new session on the site. It should be obvious, but how do I do it?
Asked
Active
Viewed 86 times
0
Aqua the SeaWing
- 323
- 4
- 15
1 Answers
2
Just check if the Session object exists or not yet using an IF statement, and if it doesn't, it means it's a new session in which you can run your counter code.
More info on working with sessions: Check whether a session is new in PHP
Community
- 1
- 1
Samuel MacLachlan
- 1,696
- 14
- 21
-
Ah, thanks. I'll try that. If it works I'll be sure to accept the answer. :) – Aqua the SeaWing Jan 03 '15 at 14:38
-
Thanks, it seems to work. Could you quickly help me test it by opening http://basicedit.maritimers.ca/basicedit? (Scroll your mouse to the very bottom of the page and hover over the bar, and it should show the view count.) – Aqua the SeaWing Jan 03 '15 at 14:44
-
1Seems to work. Showed 2 active users on the site no matter how many times I refreshed it. Nice work. – Samuel MacLachlan Jan 03 '15 at 14:48
-
Thank you. You really helped. :D – Aqua the SeaWing Jan 03 '15 at 14:49