Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

readfile

Outputs the contents of a file.

Syntax

readfile(string $filename): int|false

Parameters

ParameterTypeDescription
$filenamestringThe 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 2

Sending 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

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.

Thanks for reading!

Donate to the site — we work hard for you.