question about writing to files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

question about writing to files

Post by jaymoore_299 »

I have an in.php script for my main page in which it keeps track of where each visitor came from with http_referer. When a surfer comes from a referer that I know of, then I write to a file with that info, updating previous entries.

If I have many visitors at one time, could it be possible that the file would be opened and manipulated simultaneously by two or more users, possibly leading to data corruption? I could lock the file, but then I will not be able to get all the data. I'm wondering if this could happen, and if it does happen, how frequently does it occur?

What are some way to prevent this? Would storing my information in a database solve this? (I prefer files as it is often faster and easier to get data)
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

if 2 people are writing to the same file at the same time it can very easily cause data corruption. use a database because they are about a billion times better
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

Post by jaymoore_299 »

this would never happen with databases? Why is that?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Because that problem existed since the very beginning of computing, and thus it's very likely other people have been working on a good solution for it...

Your DBMS of choice will have a manual section on transactions... There you can find everything (and more).
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

Post by jaymoore_299 »

just wondering, could there be a problem from two users reading a file at the same time so that the data read is incorrect? Or is this only a problem for writing simultaneously?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

You may want to read something like http://www.firstsql.com/tutor5.htm, especially the section on Transaction Isolation... It explains some issues that exist (even with sql) but exist even more if you use flat files
Post Reply