PHP stream_set_write_buffer() Function
The stream_set_write_buffer() function is an inbuilt function in PHP that is used to set the buffer size for write operations on a given stream.
Syntax:
stream_set_write_buffer(resource $stream, int $size): int
Parameters: This function accepts two parameters that are described below.
- $stream: The stream resource to set the buffer size for.
- $size: The desired buffer size in bytes. The write operation will be unbuffered for the 0 size value. For this, all the writes with fwrite() will be completed, so that the write operation will be permitted for all other processes for that specific output stream.
Return Values: The function returns 0 on success and returns other values on failure.
Example 1: The following program demonstrates the stream_set_write_buffer() function.
PHP
<?php
$stream = fopen ( "example.txt" , "w" );
if (stream_set_write_buffer( $stream , 1024)) {
echo "Buffer size set successfully." . PHP_EOL;
} else {
echo "Failed to set buffer size." . PHP_EOL;
}
fwrite( $stream , "Learning computer science is really fun!" );
fclose( $stream );
?>
|
Output:
Buffer size set successfully.
Example 2: The following program demonstrates the stream_set_write_buffer() function.
PHP
<?php
$stream = fopen ( "example.txt" , "w" );
if (stream_set_write_buffer( $stream , 4096)) {
echo "Buffer size set successfully." . PHP_EOL;
} else {
echo "Failed to set buffer size." . PHP_EOL;
}
$data = str_repeat ( "Learning computer science is fun!" , 1000000);
$chunk_size = 4096;
$data_len = strlen ( $data );
for ( $i = 0; $i < $data_len ; $i += $chunk_size ) {
fwrite( $stream , substr ( $data , $i , $chunk_size ));
}
fclose( $stream );
?>
|
Output:
Buffer size set successfully.
Reference: https://www.php.net/manual/en/function.stream-set-write-buffer.php
Last Updated :
19 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...