Potentially write to the same file in PHP several times in a row?

I use PHP fputcsv to register votes in the application we are doing. The rest of my code roughly repeats this:

 $handle = fopen('votes.csv', 'a'); fputcsv($handle, $data); fclose($handle); 

This works flawlessly in tests. However, I have a little problem. When deployed in production, it is possible that many users will access this script at the same time. I'm curious how PHP will handle this.

Can I have problems and lose my voice because of this? If so, what can I do to prevent this? Is the solution more complicated than just using a database? And finally, how can I check this situation when many requests will be made at the same time? Are there any things that already exist to test this stuff?

+4
source share
1 answer

Writing to a file can cause problems with concurrent users. If you insert into the database instead, you can let the database itself process the queue. If you run out of connections, this is easy to track, and you can see the load on db as you go.

Inserting into the database will be less resource intensive than adding to the file. Having said that, you will need a rather large load in order to take effect - but with the database you have an assembly in the request queue to ease the good part of the simultaneous stress.

When you send a request to the database, it actually goes into the queue for processing. It just cannot be executed if there is a timeout in your PHP code (basically, PHP is suggested to refuse waiting for a db response), and you can control this using the PHP and Apache settings), so you have a fantastic built-in buffer .

+3
source

All Articles