Stream_set_write_buffer or file locking in PHP?

I am trying to create a caching system where you can write as much data as possible (from 8 KB to 200 KB) as quickly as possible.

I am currently applying file locking functions using the following code:

$file_handle=fopen($file_name,"w"); flock($file_handle,LOCK_EX); fwrite($file_handle,$all_data); flock($file_handle,LOCK_UN); fclose($file_handle); 

Is this the most optimal way, allowing only one process at a time to write to the file, if many of them are running the same script at the same time, or should I also include stream_set_write_buffer($file_handle,0); or should i lock the file

+4
source share
1 answer

In short:

 file_put_contents($file_name, $all_data, LOCK_EX); 

Long story: You have one problem with your code: the w mode truncates the file before the lock is received. If two separate processes truncated a file, than one writes 200Kb, than the other writes 8Kb, you will have 192Kb of garbage left in your file. I would recommend opening the file in c mode and truncating it at the end, after all the data has been written:

 $file_handle = fopen($file_name, 'c'); stream_set_write_buffer($file_handle, 0); // try to disable write buffering flock($file_handle, LOCK_EX); fwrite($file_handle, $all_data); // write to possibly pre-allocated space ftruncate($file_handle, strlen($all_data)); // remove gabage left from previous write fflush($file_handle); // flush write buffers if enabled flock($file_handle, LOCK_UN); fclose($file_handle); 

'c' Open the file for writing only. If the file does not exist, it is created. If it exists, it is not truncated (unlike "w"), and the call to this function is not performed (as is the case with "x"). The file pointer is located at the beginning of the file. This can be useful if you need to obtain an advisory lock (see Flock ()) before trying to modify the file, since using "w" can trim the file before the lock is obtained (if truncation is required, ftruncate () can be used after a lock request).

You must ensure that the write buffer is reset before the lock is released by calling fflush() or disabling write buffering. Since stream_set_write_buffer(); may fail, it is better to have fflush() . Also note that write buffering is designed to improve sequential write performance. Since you only perform one write operation, the write buffer may slow performance a bit, so it is best to disable it first.

+1
source

All Articles