Current Location: Home> Latest Articles> PHP Function readfile() Introduction: How to Output File Content to Browser or Files

PHP Function readfile() Introduction: How to Output File Content to Browser or Files

M66 2025-07-27

PHP Function readfile() Introduction: How to Output File Content to Browser or Files

In PHP, the readfile() function is a very useful tool that allows you to output the contents of a file to the browser or directly to another file. Using the readfile() function, you can easily implement file download and file copy operations.

Syntax of the readfile() Function

The basic syntax of the readfile() function is as follows:

int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )

This function takes a file path as an argument and directly outputs the contents of that file to the browser or a specified file. Its return value is the number of bytes read, and it returns false if the reading fails.

Example: Outputting File Content to Browser

Suppose we have a file named data.txt with the following content:

Hello, World!
I am learning PHP.

To output this file's content to the browser, we can use the readfile() function. Here is the implementation code:

<?php
$file = 'data.txt'; // File path

if (file_exists($file)) {
    header('Content-Disposition: attachment; filename=' . basename($file)); // Download file
    header('Content-type: text/plain'); // Set the file type to plain text
    readfile($file); // Output the file content
} else {
    echo 'File does not exist.';
}
?>

In this code, we first check if the file exists. If it does, we set the HTTP headers to specify the download method and use the readfile() function to output the file content.

When this code is executed in a browser, it will automatically download and save the data.txt file.

Output File Content to Another File

In addition to outputting content to the browser, the readfile() function can also write the file content to another file. You just need to set the second parameter to the path of the target file. Here's an example:

<?php
$sourceFile = 'data.txt'; // Source file
$targetFile = 'output.txt'; // Output target file

if (file_exists($sourceFile)) {
    readfile($sourceFile, $targetFile); // Output the file content to the target file
} else {
    echo 'File does not exist.';
}
?>

This code will copy the content of data.txt into the output.txt file.

Conclusion

By using the readfile() function, PHP developers can easily output file content to the browser or other files. This is very useful for implementing file downloads, content copying, and other file operations. Whether for simple file output or as part of more complex file handling tasks, readfile() is a very efficient and practical function.