Core\Response::startStream
Core\Response::startStream(
string $contentType,
?int $length = null,
?string $etag = null,
?string $mustEnd = null,
): Core\Response\StreamStarts a response body that your program sends in parts. startStream returns a Core\Response\Stream, and you call its write method once for each part. Use it for a large export, a long job that reports its progress, or a video.
$contentType becomes the Content-Type header, so a tainted value does not compile.
The status and the headers are sent when you call startStream, so set them first. The body ends when the program ends. Using startStream and echo in one response does not compile.
Give $length, the size of the whole body, when you know it. Then a browser can ask for one part of the body, for example to seek in a video. The stream's offset() and length() say which bytes to write. $etag is a version name for the body. A browser that resumes a download with an old name gets the whole body again.
The examples show a CSV download, the progress of a long job, an export sent one page at a time, and a video that a browser can seek in.
Parameters
$contentTypestringThe content type of the body, for exampletext/csv. It becomes a header, so ataintedvalue does not compile. It must be printable ASCII and not empty.$length?intdefault nullThe size of the whole body in bytes, ornullif you do not know it. With a size, the response has aContent-Lengthheader and a browser can ask for one part of the body, for example to seek in a video. The request headerRangesays which part. Thenoffset()andlength()of the stream say which bytes to write. Without a size, the whole body is sent andRangeis ignored.$etag?stringdefault nullA version name for the body, ornull. It is sent as theETagheader. Give a new name when the bytes change. A browser that resumes a download sends the name back, and gets the whole body if the name is old. It becomes a header, so ataintedvalue does not compile.$mustEnd?stringdefault nullA name for the body, such as the name of a download, ornull. With a name, the body is complete only after your program callsend()on the stream. If the program stops before that, the body is cut off. The browser then shows a failed download, and the error log names the body.
Return value
Returns Core\Response\Stream. A Core\Response\Stream. Call its write() method to send each part. Set the status and the headers before you call this method. Using this and echo in one response does not compile. A browser that reads this body with EventSource connects again when the body ends. For events that a page receives while it is open, use Core\Sse::upgrade.
Errors
LogicError$contentTypeis empty, or it contains a character a header cannot contain: a control character, a line break, or a character that is not ASCII. It is also thrown when$lengthis negative, when$etagcontains such a character or a", and when this request already started a body stream, because a response has one body.
Changelog
| Version | Change |
|---|---|
0.0.6 | The Core\Response methods that send a body now start with send: sendJson, sendHtml, sendText, sendBytes and sendSlotted. startStream starts a streamed response. The old names were json, html, text, bytes, slotted and stream. |
Examples
A csv download
<?nvs// Shows how to send a CSV file that the browser saves as a download.
// `Content-Disposition` tells the browser to save the body as the file `orders.csv`.// Set every header before you call `startStream`, because `startStream` sends the headers.Core\Response::setHeader('Content-Disposition', "attachment; filename=\"orders.csv\"");
// `Core\Response::startStream` starts the body and sets its content type to `text/csv`.// Each `write` sends one line of the file.Core\Response\Stream $csv = Core\Response::startStream('text/csv');$csv->write("id,customer,total\n");$csv->write("1042,Ada,19.90\n");$csv->write("1043,Alan,5.00\n");id,customer,total1042,Ada,19.901043,Alan,5.00The progress of a long job
<?nvs// Shows how a long job sends one line of progress after each step.
array<string> $steps = ['Reading the orders', 'Checking the prices', 'Writing the invoices'];
// Each `write` sends its line as soon as the step is done.// The client can show that line before the next step starts.Core\Response\Stream $log = Core\Response::startStream('text/plain; charset=utf-8');uint $done = 0;foreach ($steps as string $step) { $done = $done + 1; $log->write('Step ' . ($done as string) . ' of 3: ' . $step . "\n");}$log->write("Finished.\n");Step 1 of 3: Reading the ordersStep 2 of 3: Checking the pricesStep 3 of 3: Writing the invoicesFinished.An export one page at a time
<?nvs// Shows how to export many rows and keep only a few of them in memory.
class Customers{ // Returns one page of rows as CSV lines. // A real program reads each page from a database. public static function page(uint $number, uint $size): string { string $rows = ''; uint $i = 0; while ($i < $size) { uint $id = $number * $size + $i + 1; $rows = $rows . ($id as string) . ',customer-' . ($id as string) . "\n"; $i = $i + 1; } return $rows; }}
// The loop sends one page and then reads the next one.// Only one page is in memory at a time, however many pages there are.Core\Response\Stream $export = Core\Response::startStream('text/csv');$export->write("id,name\n");uint $number = 0;while ($number < 3) { $export->write(Customers::page($number, 2)); $number = $number + 1;}id,name1,customer-12,customer-23,customer-34,customer-45,customer-56,customer-6A video a browser can seek in
<?nvs// Shows how to send a video from storage so that a browser can seek in it.
// A real server already has the video. The example writes a short text file in its place,// so that the output is easy to read.string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'intro.mp4');Core\IO::write($path, "frame 1\nframe 2\nframe 3\n");
// With a length, the browser can ask for any part of the video with a `Range` header.// `"intro-1"` is the version name. A real program stores one with each video.Core\Response\Stream $video = Core\Response::startStream('video/mp4', Core\IO::size($path) as int, 'intro-1');
// The loop reads the part the browser asked for, 64 KiB at a time.// This request has no `Range` header, so the part is the whole file.Core\IO\File $file = Core\IO::open($path, Core\IO::FileMode::Read);$file->seek($video->offset() as uint);int $left = $video->length();while ($left > 0) { uint $size = 65536; if ($left < 65536) { $size = $left as uint; } string $piece = $file->read($size); if ($piece == '') { // The file is shorter than its size said. The connection is closed. break; } $video->write($piece); $left = $left - (Core\Bytes::length($piece as bytes) as int);}$file->close();frame 1frame 2frame 3