Core\Response::sendText
Core\Response::sendText(string $body): voidCore\Response::sendText( string $body, ): void
Sends plain text as the response. It also adds the header Content-Type: text/plain; charset=utf-8, so the browser shows the body as text and not as a page.
The body is a string, and it is sent exactly as it is. Nothing is escaped or changed. Text from a visitor is allowed. The server also sends the header X-Content-Type-Options: nosniff, so a browser never reads the text as HTML. A <script> tag in the text is shown as text and does not run.
Use Core\Response::sendHtml for a page, sendJson for data that a program reads, and sendBytes for any other content type. Using sendText and echo in one response does not compile.
The examples show a health check, text from a visitor, and a robots.txt file built from a list.
Parameters
$bodystringThe text to send. It is sent exactly as it is. Ataintedvalue is allowed: the server also sendsX-Content-Type-Options: nosniff, so a browser never reads the text as HTML.
Return value
Returns void. Nothing. Using this and echo in one response does not compile.
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 health check
<?nvs// Shows how to answer a health check with one short line of text.
// A load balancer calls this address to test that the server is running.// `Core\Response::sendText` sends "ok" with the content type `text/plain; charset=utf-8`.Core\Response::sendText("ok\n");okText from a visitor
<?nvs// Shows that text from a visitor is sent exactly as it is.
// The address is `/echo?message=...`, and the visitor chooses the value of "message".tainted string $message = Core\Request::queryParameter('message') ?? '';
// A plain text body is never shown as a page, so the `<b>` tags are not HTML here.// The browser shows them as they are. This prints "You wrote: <b>hello</b>".Core\Response::sendText('You wrote: ' . $message . "\n");You wrote: <b>hello</b>A robots txt file
<?nvs// Shows how to send the `robots.txt` file that tells search engines which pages to skip.
array<string> $private = ['/admin/', '/basket/', '/account/'];
// The first line says that the rules are for every search engine.// Each private path then becomes one `Disallow:` line.string $robots = "User-agent: *\n";foreach ($private as string $path) { $robots = $robots . 'Disallow: ' . $path . "\n";}$robots = $robots . "Sitemap: https://example.com/sitemap.xml\n";
Core\Response::sendText($robots);User-agent: *Disallow: /admin/Disallow: /basket/Disallow: /account/Sitemap: https://example.com/sitemap.xml