What is the readfile() function in PHP?

The readfile() function in PHP is a built-in function that reads the contents of a file and writes the content to the output buffer.

Syntax

readfile(string $filename, bool $include_path, resource $context ): int|false


Parameters

filename: This specifies the filename we have to read.

include_path: This is an optional parameter. We set this parameter to true if we want to search the file in the include_path (in php.ini).

context: This is an optional parameter that specifies the behavior of the stream.

Return value

If the readfile() function is executed successfully, it returns the number of bytes read. Otherwise, in case of any error, it returns false.

Code

The following code demonstrates how to use the readfile function.

main.php
test.txt
<?php
echo readfile("test.txt");
?>

Explanation

In the code above, invoking the readfile function writes the content of the file to the output buffer. This is then displayed on the console, along with the number of bytes read.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved