skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. Based on your sandbox/online environment:

    Why stream_set_write_buffer() might fail

    • Filesystem-specific restrictions: Some filesystems (network drives, configs of NFS) may restrict or ignore buffer size adjustments.
    • PHP config or environment: The PHP installation might be running in an environment (containers or read-only modes) that restricts file I/O or buffering settings.
    • Stream type does NOT support buffering

    Stream types and their support

    Stream Supports Buffering?
    Regular Files Yes
    php://output No
    php://stdout No
    Network Streams Depends
    Sockets Depends
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search