Downloading Files
The download() method serves a file to the browser using Trongate's built-in $this->file->download() method. It looks up the record in the database, verifies the file exists on disk, and then initiates the download.
The Controller Method
public function download(): void {
$this->gatekeeper();
$update_id = segment(3, 'int');
if ($update_id === 0) {
$this->not_found();
return;
}
$data = $this->model->get_file_by_id($update_id);
if ($data === false) {
$this->not_found();
return;
}
$file_path = $data['file_path'];
if (file_exists($file_path)) {
$this->file->download($file_path);
} else {
show_error(
'The requested file could not be found '
. 'on the server.'
);
}
}How It Works
-
Authenticate - The
gatekeeper()call ensures only logged-in administrators can download files. -
Look up the record - The database record provides the
file_pathstored during upload. -
Verify the physical file -
file_exists()checks that the file is actually present on disk. It is possible for a database record to exist but the file to be missing (deleted manually, moved, etc.). -
Serve the file -
$this->file->download()sends the appropriate HTTP headers and streams the file contents to the browser.
The file->download() Method
Trongate's $this->file->download() handles all the HTTP mechanics:
- Sets
Content-Typebased on the file's MIME type - Sets
Content-Disposition: attachmentto force a download dialog - Sets
Content-Lengthso the browser shows a progress bar - Streams the file in chunks to handle large files without memory issues
- Calls
exit()after sending, preventing further script execution
The method accepts a relative path - the same file_path stored in the database during upload. It also accepts an optional second parameter:
// Display inline (e.g., PDF in browser) instead of download
$this->file->download($file_path, false);
When the second parameter is false, the file is displayed inline rather than as an attachment download. This is useful for PDFs that you want the browser to render directly.
Error Handling
There are two failure scenarios handled explicitly:
-
Record not found (invalid ID or deleted record) - The
not_found()helper renders a "File Not Found" page. -
File missing from disk (database record exists but file was deleted manually) -
show_error()displays an error message through the admin template.
The second scenario is worth emphasizing: always verify the physical file exists before calling download(). A missing file will cause an error in the download method, so check first and present a helpful message if the file is absent.
We're continually improving the Trongate documentation. If anything is incorrect, unclear, incomplete, or could be better, we'd genuinely appreciate your input.
Share your thoughts in the Documentation Feedback.