Using PHP readfile() to Output File Contents to Browser or Another File
This article explains PHP's readfile() function, its syntax, return values, and demonstrates how to use it to output a file's contents to the browser or copy it to another file, including example code and handling of missing files.
In PHP, the readfile() function is a convenient way to read a file and send its contents directly to the browser or another output stream.
The function signature is:
int readfile ( string $filename [, bool $use_include_path = FALSE [, resource $context ]] )It takes a filename as its first argument, returns the number of bytes read on success, and false on failure.
Consider a text file data.txt with the following content:
Hello, World!
I am learning PHP.The following PHP script demonstrates how to output this file to the browser, setting appropriate HTTP headers for a download:
<?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 MIME type
readfile($file); // output file content
} else {
echo "File does not exist.";
}
?>The script first checks that the file exists, then sends headers to suggest a download and specifies the content type before calling readfile() to stream the file.
When executed, PHP outputs the contents of data.txt and prompts the user to save a file named data.txt .
The readfile() function can also be used to copy a file’s contents to another file. The example below shows 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.";
}
?>Running this script copies the content of data.txt into output.txt . In both cases, readfile() provides a simple method for file output, whether for downloading or copying.
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.