readfile
Outputs the contents of a file.
Syntax
readfile(string $filename): int|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $filename | string | The path to the file. |
Return value
int|falseThe number of bytes output, or `false`.
Examples
Outputting a file:
<?php
$file = sys_get_temp_dir() . '/ref-readfile.txt';
file_put_contents($file, "line 1\nline 2");
readfile($file);Output:
line 1
line 2Sending a file as a download:
<?php
// download.php
$file = __DIR__ . '/files/report.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="report.pdf"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;Notes
The function does not load the whole file into memory, so it suits large files too.
See also
- file_get_contents — Reads a whole file into a string.
- header — Sends an HTTP response header.
- filesize — Returns the size of a file in bytes.
Related recipes
In the tutorial
- HTTP requests and responses — How PHP receives a request and builds a response — the request method and address, headers, status codes, redirects and JSON responses.