php read & write from file at the same time
Basically I have an XML file to populate data with and I will have a cron (in PHP) that updates it every 5 minutes. But at the same time, I will have users accessing this file all the time (and I'm talking about thousands of users).
When I tried a script myself by writing 2million text lines in a .txt file and reading it at the same time, of course the file_get_contents()
was getting the current text in the .txt file and does not wait for it to end and get the contents when it's finished. So what I did is, I write to a temporary file and then rename it to the original .txt file. The renaming process on my PC takes up 0.003 seconds (calcu开发者_StackOverflow中文版lated using microtime()
).
Do you think this is a suitable solution or there will be users which will end up having an error that the file does not exists?
Of course this is not suitable.. You have to lock the file in this 0.003 microseconds.
A very simple way is a flag
For example create file called isReplacing
After replacing is done, delete file isReplacing
When a user wants the file say in getfile.php
while(file_exists("isReplacing"))
{}
//NOW echo file_get_contents()
//BETTER:
if(file_exists("isReplacing"))
{
//GET DATA FROM DATABASE
}
else
{
//ECHO THE FILE
}
NOTE this is a dumb way but I just want to demonstrate
精彩评论