Question

I am working on a very simple and small visitor counter and I am wondering myself if it is not too heavy to on the server resources to open a MySQL database every time a visitor enters on a page of the website.

Some people store the visits on a plain-text file and maybe I could store the number in a session (in an array with a key for each page), and when the session is closed, I copy it in the database in one time?

What is the lightest way to do this?

Was it helpful?

Solution

In most robust web applications, the database is queried on every page load anyway for some reason or another, so unless you have serious resource limits you're not going to break the bank with your counter query or save much load time by avoid it.

One consideration might be to increase the value of the database update so that one update can be queried for multiple uses. In your case, you could have a view log, like :

INSERT INTO view_log 
VALUES (user_name, ip_address, visit_timestamp, page_name)

Which could be used for reporting on popularity of specific pages, tracking user activity, debugging, etc. And the hit count would simply be:

SELECT COUNT(1) FROM view_log

OTHER TIPS

If your site has a database already, use it!

Connections are most likely pooled between opens and take very little effort.

If you write to a file the site requires write access to it and you risk concurrency problems during multiple user connections.

Only persisting when session closes is also a risk if the server is closed abruptly..

Most sites open a MySQL connection anyway, so if you do, you won't have to open it twice. Writing to disk also takes resources (although probably less), and additionally you might wear out a small part of your disk very fast if you have a file based counter on a busy website. And those file writes will have to wait for each other, while MySQL handles multiple requests more flexible.

Anyway, I would write a simple counter interface that abstracts this, so you can switch to file, MySQL or any other storage easily without having to modify your website too much.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top