Results 1 to 5 of 5
Thread: Writing High Scores to a File
Jul 13, 2009, 15:21 #1
Writing High Scores to a File
I'm developing a flash game and there is a high scores table in it I'm working on.
I'd like to use a simple text file to read/write high scores with PHP.
The potential problem is that if there occurs multiple request to write to the file, the file/data might be corrupted. Is that right?
Should I lock the file while writing? If so what happens another user submits a score while the file is locked? How to solve this?
I hope the problem is clear enough.
I'll switch to a database if the problem I tried to explain really exists and the solution is complicated.
Jul 13, 2009, 15:35 #2
Yes, you can lock the file, look at this function
as a third argument put LOCK_EX
But I think the plain text file may not be the best way to store data. I mean, if all you have to store is just one line with a value of high score, then sure, a text file is fine, but if you also want to store username => score pairs then you should consider using an xml file.
Jul 13, 2009, 16:36 #3
Well I agree XML would be more compatible and expandable but user/score pairs are pretty easy to handle with TXT as well (plus shorter data).
Anyway back to my actual problem:
Suppose I locked the file while someone is submitting score. What happens another user submits at the same time? I guess it will fail isn't it? What is your solution to this issue?
As far as I know, multiple simultaneous writes/updates is not an issue in SQL databases. I think it would be hard to queue the requests if I go through the text/XML file path.
Jul 13, 2009, 16:39 #4
Yes, if the file is locked, php will wait untill lock is removed. As soon as lock is removed it will obtain its own lock and write to file
The queue is handled by file system, you don't need to worry about it, just like with database. It's actually may be more problematic with some databases because unless the row level locking is available, the entire table is locked when a process writes data to a table.
If you use mysql with default table format then row level locking is not available.
Jul 13, 2009, 16:46 #5