View Full Version : Quick Question: TXT File or MySQL Database?

08-09-2007, 11:51 PM
I'm planning on making a small hit counter that anyone could sign up to use on a site. However, first I need to choose a way to store data. I could either store pageload/unique hits information and configuration settings in text files, or store it all in a database. I would think txt files would be faster, but I don't know. Which method should I use?

08-09-2007, 11:59 PM
A MySQL database would be much faster than a text file although for a simple hit counter is may more hassle to create so unless you are likely to experience a large amount of traffic then a text file may be equally acceptable.
Basically if you are already using a MySQL database for other things and you feel it will be easy to add a hit counter into that then that is the most appropriate although for a low traffic easy solution a text file may be appropriate.

08-10-2007, 12:08 AM
i have one on my site for download, i dont use it, but it works fine. it uses a txt file.

if (file_exists('count.txt'))
$fil = fopen('count.txt', r);
$dat = fread($fil, filesize('count.txt'));
echo $dat+1;
$fil = fopen('count.txt', w);
fwrite($fil, $dat+1);

$fil = fopen('count.txt', w);
fwrite($fil, 1);
echo '1';

its the most simple i could make, so if you want mod it to your needs, i know your looking for somthing more complex, but sometimes non-complexity is better.

you can use it if you want. just save it and use require or include to show it.

08-10-2007, 12:48 AM
The problem is, I don't know how much traffic it will get. I'm hoping for a lot... :)

Thanks, rappa, but I already have a script like that that counts both total and unique visitors (using a cookie, though I may add support for IP address checking). Opening the file twice is a good idea. In mine, I opened it once to read and write, read it, truncated it, and wrote new data to it. I had some problems doing that way, but eventually (with help lol) got it to work.

If I used text files, I would have made it so that it creates two per user--one that holds settings (like background and text colors, and maybe even stuff like a list of IP addresses to block) and one that contains the number of total and unique visitors. A database would probably be easier (especially since I can create counter ID numbers based on the number of rows in the database, instead of having to make a text file that counts this). I could even just use one table for both hits and settings, instead of two text files.

Long story short, I'll probably just use a database. Thanks!

Oh, and what might I have to worry about as far as security (like SQL injection)? Can I prevent this by just escaping strings?