The php Function Stream_Set_WriteBuffer
In the age of JavaScript this and that, PHP remains the OG programming language for web development, and WordPress—built in PHP—still powers 25% of the internet at large. In this article, we’ll explore a little-used but very important php function: stream_set_write_buffer.
A stream is the way of generalizing files, networks, data compression, and other operations that have a common set of functions and uses. The basic idea is that a stream is something which can be read from or written to in a linear fashion, and may also be fseek()ed to an arbitrary location within the stream. Streams are the foundation of everything we do on the web, and understanding them is essential for front-end developers.
There are a variety of wrappers (add-on code that tells the stream how to handle specific protocols/encodings) built into PHP by default, and additional, custom wrappers can be added either within a script using stream_wrapper_register(), or via extension.
When writing to a file in PHP, output using fwrite() is normally buffered at 8K. This means that if two processes write to the same file at the same time, each will write up to 8K before pausing and allowing the other to continue. This is intended to improve performance, but it can reduce speed if you’re only writing a few bytes at a time.
To prevent this from happening, you can use the php function stream_set_write_buffer() to disable output buffering for a file. This will reduce the amount of CPU time spent writing to a file, but you’ll need to ensure that any IO is flushed by calling fflush() afterwards.