Welcome to WebmasterWorld Guest from 188.8.131.52
I've been asked to put together a survey for a client with no db access. Clearly text files are the way forward but what if 2 people try to vote at once?
Is this a problem, and if so, is flock() the way forward?
I read the manual entry on it but am none the wiser? (well, not much anyway)
Yep, simultaneous users writing to a file can cause nasty problems. Flock (File Lock) will prevent that if used correctly - see these threads for more info:
The basic syntax for flocking in PHP is:
$pointer=fopen ( $filename, "w+"); # open your file for reading and writing
flock ($pointer, "LOCK_EX"); # lock your file
# do stuff to the file here
flock ($pointer, "LOCK_UN"); # unlock your file
fclose($pointer); # close the file
Note: it may not actually be necessary to unlock the file before closing it - Perl does this automatically, but I'm not sure about PHP.
If the 'survey' has 4 possible answers: a, b, c and d then all you need do is append either of the above letters to the end of the file that records the results.
You end up with a file like this:
The size of the file is the total amount of votes, and substr_count() will return the number of times a letter occors to give you the individual votes!
Neat huh? No locking, no messing, no worrying about simultaneus read/writes, brilliant!
all you need do is append either of the above letters to the end of the file that records the results.
But how does this solve the original problem?
Granted, you won't need to open the file to get the total number of votes. But you must still open the file to read the individual votes or to cast a vote.
So at the risk of repeating what you already know/have considered..I'm worried about file corruption and loss of data. If two users both cast a vote and the server spins two threads accessing the same file at the same time you could be in for a surpize. Here's a thread on the subject:
I promise to let this alone now.:)