Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure the size of the internal buffer for file IO in PHP?

Tags:

php

I want to change the buffer size for file IO while reading/writing to files from PHP, but the only way to do so is stream_set_write_buffer() which always return -1. I couldn't find any error descriptions with error_reporting(E_ALL); or whatever.

I have a live example that reproduces the problem: https://onlinephp.io/c/5955f

I am asking for help, why does it fail? How to make it work and what am I missing? No docs helped me so far.

like image 633
Dmitriy Lezhnev Avatar asked Nov 23 '25 00:11

Dmitriy Lezhnev


1 Answers

Here is a workaround:

fsync($f);
$err = stream_set_write_buffer($f, 65536);

Why does it fail?

stream_set_write_buffer sets the buffer through setvbuf

if (data->file == NULL) {
    return -1;
}
...
return setvbuf(data->file, NULL, _IOFBF, size);

But PHP's fopen function doesn't call C's fopen function, but instead calls the open system call, which returns a file descriptor, so this file field is a null:

static php_stream *_php_stream_fopen_from_fd_int(...)
{
    ...
    self->file = NULL;
    ...
}

Then I searched this file and found a function called php_stdiop_cast that sets the file field:

data->file = fdopen(data->fd, fixed_mode);

And this function is called by another function called php_stdiop_sync, which is the implementation of fsync and fdatasync functions.

like image 169
shingo Avatar answered Nov 25 '25 13:11

shingo