# fpassthru should get an optional length argument

- Thread: https://externals.io/message/116299
- Original archive: https://news-web.php.net/php.internals/116299
- Started by Hans Henrik Bergan on 2021-10-30T09:39:07+00:00
- Messages: 2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #116299 — Hans Henrik Bergan — 2021-10-30T09:39:07+00:00

URL: https://externals.io/message/116299#116299

ref https://bugs.php.net/bug.php?id=39135 ,
i was thinking about how to implement HTTP Range requests/HTTP 206 Partial
Content in userland php,
 and ofc it's possible to implement using `fread()` loops, but it'd be easier
(and faster? presumably) to implement if `fpassthru()` natively supported a
$max_bytes=null argument,

an example of where it would be useful:

<?php
$h=tmpfile();
fwrite($h,"123456789ABCDEF");
// this is _NOT_ a proper http-range-parser!
$range = $_SERVER['HTTP_RANGE'] ?? "bytes=5-9";
$range=explode("-",explode("=",$range,2)[1],2);
$start = (int)$range[0];
$byte_count = (-$start) + ((int)$range[1]) + 1; // the range format is
weird.. "Range: bytes=5-5" means "seek to byte #5 and serve 1 byte", 5-6
means "seek to byte #5 and serve 2 bytes"~
fseek($h,$start,SEEK_SET);
http_response_code(206); // HTTP 206 Partial Content
//echo fread($h,$byte_count); // << this is not suitable for large files,
if 1GB bytes is requested, this will use 1GB ram...
fpassthru($h, $byte_count);
// should print 6789A

---

## #116301 — Pierre — 2021-10-30T11:32:54+00:00

URL: https://externals.io/message/116299#116301 · In reply to: #116299

Le 30/10/2021 à 11:39, Hans Henrik Bergan a écrit :
> ref https://bugs.php.net/bug.php?id=39135 ,
> i was thinking about how to implement HTTP Range requests/HTTP 206 Partial
> Content in userland php,
>   and ofc it's possible to implement using `fread()` loops, but it'd be easier
> (and faster? presumably) to implement if `fpassthru()` natively supported a
> $max_bytes=null argument,
>
> an example of where it would be useful:
>
> <?php
> $h=tmpfile();
> fwrite($h,"123456789ABCDEF");
> // this is _NOT_ a proper http-range-parser!
> $range = $_SERVER['HTTP_RANGE'] ?? "bytes=5-9";
> $range=explode("-",explode("=",$range,2)[1],2);
> $start = (int)$range[0];
> $byte_count = (-$start) + ((int)$range[1]) + 1; // the range format is
> weird.. "Range: bytes=5-5" means "seek to byte #5 and serve 1 byte", 5-6
> means "seek to byte #5 and serve 2 bytes"~
> fseek($h,$start,SEEK_SET);
> http_response_code(206); // HTTP 206 Partial Content
> //echo fread($h,$byte_count); // << this is not suitable for large files,
> if 1GB bytes is requested, this will use 1GB ram...
> fpassthru($h, $byte_count);
> // should print 6789A
>
Hello,

Can't you use `fseek()` and `stream_copy_to_stream()` to achieve what you're 
trying to do without consuming memory ?

Regards,

--

Pierre
