Mastering PHP’s readfile(): Quick File Output and Download Guide

Learn how to use PHP’s readfile() function to effortlessly output file contents to the browser, trigger downloads, and copy files, with clear syntax explanations, example code, and handling of file existence checks.

php Courses
php Courses
php Courses
Mastering PHP’s readfile(): Quick File Output and Download Guide

In PHP, the readfile() function is a convenient way to output a file’s contents directly to the browser or another file.

Syntax:

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

The function takes a filename, reads the file, and outputs its content. It returns the number of bytes read, or false on failure.

Example file data.txt:

Hello, World!
I am learning PHP.

To send this file to the browser for download:

<?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 checks that the file exists, sets appropriate HTTP headers, and then calls readfile() to output the file.

Running the script will cause the browser to download data.txt containing the file’s text. readfile() can also write a file’s contents to another file. By providing a target path as the second argument, you can copy the source file:

<?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 execution, the contents of data.txt are written to output.txt. Using readfile() thus simplifies file output for both browser downloads and file copying.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPfile-handlingDownloadreadfile
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

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.