Using PHP readfile() to Output File Contents to Browser or Another File
This article explains the PHP readfile() function, its syntax and return values, and provides step‑by‑step examples showing how to display a text file in the browser, force a download, and copy its contents to another file using simple PHP code.
The readfile() function in PHP is a convenient built‑in function that reads a file and writes its contents directly to the output buffer, allowing the file to be sent to a browser or another destination.
Its syntax is: int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )
The function takes the filename as a required argument, optionally uses the include path, and can accept a stream context. It returns the number of bytes read on success or false on failure.
Assume we have a file data.txt with the following content: Hello, World! I am learning PHP.
To output this file to the browser and trigger a download, we can use the following PHP code:
<?php
$file = 'data.txt'; // file path
if (file_exists($file)) {
header('Content-Disposition: attachment; filename=' . basename($file)); // download header
header('Content-type: text/plain'); // set MIME type
readfile($file); // output file content
} else {
echo "File does not exist.";
}
?>The script first checks whether the file exists, sets appropriate HTTP headers for a file download, and then calls readfile() to stream the file contents to the client.
When executed, PHP will send the contents of data.txt to the browser, which can be saved as a downloaded file.
The readfile() function can also be used to copy a file’s contents to another file. The following example demonstrates this usage:
<?php
$sourceFile = 'data.txt'; // source file
$targetFile = 'output.txt'; // destination file
if (file_exists($sourceFile)) {
readfile($sourceFile, $targetFile); // output to target file
} else {
echo "File does not exist.";
}
?>After running this script, the contents of data.txt are written into output.txt , effectively copying the file.
Overall, the readfile() function provides a simple and efficient way to output file data for downloads, display, or file copying, making it a highly useful tool in PHP backend development.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.