Serving downloads
Stream it straight to the browser
Pass a writable stream as sink, and the bytes go there as they are produced.
Nothing is buffered, so the first bytes leave before the last section is read
from your database.
use MejiroEPUB\Document;
use MejiroEPUB\DocumentInfo;
use MejiroEPUB\Text\Notation;
use MejiroEPUB\Text\WritingMode;
// Headers first: once the Document exists, bytes are on their way.
while (ob_get_level() > 0) {
ob_end_clean();
}
header('Content-Type: application/epub+zip');
header('Content-Disposition: ' . epubDisposition($novel->title));
header('X-Content-Type-Options: nosniff');
set_time_limit(0);
$book = new Document(
new DocumentInfo(title: $novel->title, language: 'ja', author: $novel->author,
identifier: $novel->url, publisher: 'Example Novels'),
writingMode: WritingMode::VERTICAL_RL,
notation: Notation::novel(),
sink: fopen('php://output', 'wb'),
);
foreach ($episodes as $episode) { // e.g. an unbuffered database cursor
$book->section($episode->title, $episode->body);
}
$book->finalize(); // not save() or output(): the bytes are already sent
With a sink, save() and output() throw a LogicException — there is no
buffer left to hand over. Call finalize().
There is no Content-Length: the size is not known until the end. Browsers
handle that fine; they just cannot show a percentage.
Name the file after the work
Some reading systems put the file name on their shelf (see Metadata), so the file name is what your reader sees. Send the title, UTF-8 encoded as RFC 5987 describes, with an ASCII fallback for old clients:
function epubDisposition(string $title): string
{
// Characters no file system will take, and control characters.
$name = preg_replace('/[\\\\\/:*?"<>|\x00-\x1F\x7F]/u', '', $title) ?? '';
$name = trim($name) !== '' ? trim($name) : 'book';
return sprintf(
'attachment; filename="book.epub"; filename*=UTF-8\'\'%s',
rawurlencode($name . '.epub'),
);
}
When something fails half-way
Once bytes have been sent, an exception cannot become an error page: the headers are gone, and the browser keeps a truncated file. Two ways to handle it:
- Check what can be checked first. Image files are the usual failure — make sure they exist and are readable before you send headers.
- Build to a file, then send it. Without a sink,
save()writes the finished EPUB to a path; serve that withreadfile(). Memory use is the same (the library still streams, into a temporary buffer), and an exception happens before the first header. This also gives you a file to cache, which is worth having when the same work is downloaded often.
$path = sys_get_temp_dir() . '/novel-' . $novel->id . '.epub';
$book->save($path); // throws here, before anything is sent
header('Content-Type: application/epub+zip');
header('Content-Disposition: ' . epubDisposition($novel->title));
header('Content-Length: ' . filesize($path));
readfile($path);