Hey everyone!
Recently I came across a feature request for PHP on GitHub issues:
https://github.com/php/php-src/issues/9673.
In short, this user would like to have an additional optional
?int $length = null
parameter to the fpassthru function.
Currently the fpassthru function will output every remaining byte of
the stream to the output of PHP's process.
With a $length parameter you could limit how many bytes of the stream
are outputted. For example, if you'd call fpassthru($my_stream, 3)
,
at most 3 bytes will be outputted. Passing null or not giving a
$length parameter will result in outputting all the remaining bytes,
just like it is the case now.
The concrete use-case for the issue reporter is to implement HTTP range
requests in a convenient way. The current workaround is to use the
stream_copy_to_stream function in conjunction with php://output
(see the first comment on the GitHub issue).
stream_copy_to_stream does have a length argument to limit how many
bytes are copied.
Reasoning:
I think that adding an optional $length parameter to fpassthru makes
a lot of sense because it is analogous with how other functions behave.
For example, the fgets, fwrite, fputs, file_get_contents,
stream_copy_to_stream and stream_get_contents all have such a
length-limiting parameter. The behaviour of $length would be in line
with how these functions behave.
Scope:
There's also the SplFileObject::fpassthru function and the gzpassthru
function. Both of these functions would also get the additional
optional $length parameter to be consistent with the
fpassthru function, and behave in the same way.
BC:
There is one backwards compatibility break unfortunately.
If a user made a class that extends SplFileObject and their class has
the fpassthru method, they have to change the signature and
implementation in order to be compatible with the changed method.
Other than that I don't see new issues.
Implementation:
I already made an implementation of this feature as a PR:
https://github.com/php/php-src/pull/10476.
Even though there's 220 newly added lines of code, most of the
added code is actually in tests. Only a small portion of the
added code are changes to PHP itself.
Therefore I think that adding this feature is not very disruptive.
Questions:
My gut feeling says that I probably need to go through the RFC process
in order to be able to introduce this feature?
In any case, I would like to get feedback on this proposal:
- How do you feel about this?
- Is this something that you feel is good to add to PHP?
- Do you have concerns or objections?
Looking forward for replies :)
Cheers
Niels