Skip to content

Core\Response::sendFile

Sends a file from the disk as the whole response. Use it for a download, a PDF or an image. The program gives only the path. The server reads the file in small pieces, so a large file does not use the memory of the program.

The server chooses the content type from the file name: .html is sent as HTML and .csv as CSV. A browser can also ask for only part of the file. This lets it jump to any point in a video, and resume a download. If the file changed, the browser gets the whole new file. When a request calls sendFile more than once, it sends only the last file. Only that file counts against the max_output limit in nvs.toml.

A request may send files in its application folder, except nvs.toml and names that start with .. Other paths need the fs.read capability in nvs.toml. A path that is not allowed throws a RuntimeError. A missing file throws an IOError, and a folder throws a LogicError. A path from the request is tainted, which means it comes from outside the program. A tainted path does not compile here.

Parameters

  • $pathstringThe file to send. fs.read in nvs.toml must allow it. A tainted value does not compile, because the path decides which file is read. To give a download its own name, set Content-Disposition with Core\Response::setHeader.

Return value

Returns void. Nothing. The server also responds to a browser that requests only part of the file, so a browser can jump to any point in a video and resume a download that stopped. If the file changed since the download started, the browser gets the whole new file. Using this and echo in one response does not compile.

Errors

  • RuntimeErrorfs.read does not allow $path. This error comes whether or not the file exists, the same as for Core\IO::read.
  • IOErrorThere is no file at $path, or the operating system does not allow this program to read it.
  • LogicError$path is a folder, or something else that is not a regular file. Nothing is sent.

Changelog

VersionChange
0.0.6When a request calls Core\Response::sendFile more than once, each call replaces the earlier file. The request sends only the last file. The max_output limit in nvs.toml now counts only that file.

Examples

A page saved on disk

<?nvs
// Shows how to send a file that is saved on disk as the whole response.
// A real server already has this file. The example writes it first, so that it has a file to send.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'about.html');
Core\IO::write($path, "<h1>About us</h1>\n<p>We sell tea since 1998.</p>\n");
// `sendFile` sends the file exactly as it is, and reads it in small pieces.
// The content type is `text/html`, because the file name ends in `.html`.
Core\Response::sendFile($path);
Output
<h1>About us</h1>
<p>We sell tea since 1998.</p>

A file that does not exist

<?nvs
// Shows what happens when the file to send does not exist.
// `createTemporaryDirectory` makes a new, empty folder, so there is no file at `$path`.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'invoice-1042.pdf');
// `sendFile` throws an `IOError` when there is no file at the path.
// The program catches it and sends a short page with the status 404.
try {
Core\Response::sendFile($path);
} catch (IOError $error) {
Core\Response::setStatus(404);
Core\Response::sendText("This invoice does not exist.\n");
}
Output
This invoice does not exist.

Download a manual the visitor chose

<?nvs
// Shows how to send one file from a fixed list, chosen by the visitor.
// A real server already has these files. The example writes them first, so that it has files to send.
string $folder = Core\IO::createTemporaryDirectory();
Core\IO::write(Core\Path::join($folder, 'kettle.txt'), "Kettle: fill with water, then press the switch.\n");
Core\IO::write(Core\Path::join($folder, 'toaster.txt'), "Toaster: put the bread in, then push the lever.\n");
// Text from a request is tainted, and `sendFile` does not compile with a tainted path.
// So the program uses `?product=kettle` only to find a file name in its own list.
array<string> $manuals = ['kettle' => 'kettle.txt', 'toaster' => 'toaster.txt'];
tainted string $product = Core\Request::queryParameter('product') ?? '';
if (isset($manuals[$product])) {
Core\Response::sendFile(Core\Path::join($folder, $manuals[$product]));
} else {
Core\Response::setStatus(404);
Core\Response::sendText("There is no manual for this product.\n");
}
Output
Kettle: fill with water, then press the switch.

A download behind an access check

<?nvs
// Shows how to send a file only to a visitor who may have it, under a download name.
// A real server already has this file. The example writes it first, so that it has a file to send.
string $path = Core\Path::join(Core\IO::createTemporaryDirectory(), 'invoice-1042.csv');
Core\IO::write($path, "item,price\nTea,4.50\nCups,12.00\n");
// The check comes before `sendFile`. A visitor without the right key gets a 403 status and no file.
// A real program checks the user who is logged in. This example checks a header.
?tainted string $key = Core\Request::header('x-download-key');
if ($key == 'letmein') {
// `Content-Disposition` makes the browser save the file as `invoice.csv`.
// The browser can also resume this download if the connection stops.
Core\Response::setHeader('Content-Disposition', "attachment; filename=\"invoice.csv\"");
Core\Response::sendFile($path);
} else {
Core\Response::setStatus(403);
Core\Response::sendText("You may not download this invoice.\n");
}
Output
item,price
Tea,4.50
Cups,12.00