download()

public function download(string $file_path, bool $as_attachment = true): void

Description

Initiates a file download or displays a file inline. This method handles header preparation, including Content-Type and Content-Disposition.

This method calls exit after sending the file to prevent additional output.

Parameters

ParameterTypeDescription
$file_path string The path to the file.
$as_attachment bool (optional) Force download (true) or display inline (false). Default is true.

Example #1

The code sample below demonstrates how to allow users to download their invoice PDFs.

Method Behavior: The download() method calls exit after sending the file, which terminates script execution. This means any code placed after the download() call will not run. There's no need to add a return statement or redirect after calling this method.

Example #2

The example above shows how to display a PDF inline in the browser rather than forcing a download.

Inline Display vs Download: Setting the second parameter to false causes the file to be displayed inline in the browser (if the browser supports the file type). This is useful for PDFs, images, and text files that users may want to preview before downloading. Setting it to true (the default) forces the browser to prompt a download dialog.

Example #3

The example above demonstrates how to implement a secure download system that logs file access.