From f08b9bcbfbd94645c2050255f579951232fff468 Mon Sep 17 00:00:00 2001 From: Pierre Clavequin Date: Sat, 27 Jul 2024 00:02:36 +0800 Subject: [PATCH] feat: method to download files easily --- flight/Engine.php | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/flight/Engine.php b/flight/Engine.php index 4dd595f..e84a742 100644 --- a/flight/Engine.php +++ b/flight/Engine.php @@ -76,7 +76,7 @@ class Engine private const MAPPABLE_METHODS = [ 'start', 'stop', 'route', 'halt', 'error', 'notFound', 'render', 'redirect', 'etag', 'lastModified', 'json', 'jsonHalt', 'jsonp', - 'post', 'put', 'patch', 'delete', 'group', 'getUrl' + 'post', 'put', 'patch', 'delete', 'group', 'getUrl', 'download' ]; /** @var array Stored variables. */ @@ -895,6 +895,31 @@ class Engine } } + public function _download(string $file): void { + if (!file_exists($file)) { + throw new Exception("$file cannot be found."); + } + + $fileSize = filesize($file); + + $mimeType = mime_content_type($file); + + header('Content-Description: File Transfer'); + header('Content-Type: ' . $mimeType); + header('Content-Disposition: attachment; filename="' . basename($file) . '"'); + header('Expires: 0'); + header('Cache-Control: must-revalidate'); + header('Pragma: public'); + header('Content-Length: ' . $fileSize); + + // Clear the output buffer + ob_clean(); + flush(); + + // Read the file and send it to the output buffer + readfile($file); + } + /** * Handles ETag HTTP caching. *