Backend Development 4 min read

PHP readfile() Function: Syntax, Parameters, Return Values, and Usage Examples

This article explains the PHP readfile() function, covering its syntax, parameter details, return values, and practical examples for sending files to the browser, storing them in variables, and using include_path searches, while noting memory considerations for large files.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP readfile() Function: Syntax, Parameters, Return Values, and Usage Examples

Basic Syntax

<code>readfile(string $filename, bool $use_include_path = false, resource $context = null) : int|false</code>

Parameter Description

$filename : Path of the file to read.

$use_include_path (optional): If true, search the file in the include_path.

$context (optional): A stream context resource.

Return Value

If successful, returns the number of bytes read.

If the file cannot be opened or reading fails, returns false.

The function sends the file content to the browser or stores it in a variable, suitable for text, image, PDF files, etc.

Usage of readfile()

Read file and send to browser

Example that forces a PDF download:

<code>$file = 'example.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
</code>

Read file and store in a variable

Example using a stream context to capture progress:

<code>$file = 'example.txt';
$data = '';
$context = stream_context_create();
stream_context_set_params($context, array('notification' => function($code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) use (&$data) {
    if ($code == STREAM_NOTIFY_PROGRESS) {
        $data .= $message;
    }
}));
readfile($file, false, $context);
</code>

Note that storing large files in a variable can consume a lot of memory.

Search file using include_path

If $use_include_path is true, readfile() searches in the include_path defined in php.ini.

<code>$file = 'example.txt';
readfile($file, true);
</code>

If the file exists in one of the include_path directories, its content is returned; otherwise false is returned.

Summary

The readfile() function is a convenient way to read a file and either output it directly to the browser or capture it in a variable. It supports optional include_path searching and stream contexts, but care must be taken with large files to avoid excessive memory usage.

BackendWeb DevelopmentPHPfile handlingreadfile
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.