![]() |
VOOZH | about |
The readfile() function in PHP reads a file and writes its contents directly to the output buffer (usually the browser). It’s an easy way to show a file without reading it line by line yourself.
If there’s a problem reading the file, like if it doesn’t exist, PHP will usually show an error message. To hide these error messages, you can put an @ symbol before readfile(). This way, the errors won’t be shown.
Syntax:
readfile(filename, include_path, context)
In this syntax:
The readfile() function in PHP accepts three parameters.
Return Value:
Note: The
readfile()function was originally added in PHP 4 and continues to work smoothly in PHP 5, PHP 7, and PHP 8 versions.
When you call readfile(), PHP:
Now, let us understand with he help of the example:
Suppose you have a text file named notes.txt containing the following lines:
Welcome to PHP!
This is a demo file.
Have a great day!To output the contents of this file, you can use the following code:
Output:
This script reads the whole file and prints it, then shows the number of bytes read.
To avoid warnings when a file is missing, verify the file’s existence first:
Output:
To display an image stored on the server, you need to specify the correct MIME type before reading the file:
To force the browser to download a file instead of displaying it, use headers that instruct the browser accordingly. With this code, the file will be downloaded when accessed.
@ to hide errors if needed, but handle errors properly.The readfile() function is a useful way to quickly show the contents of a file in PHP. You can use it to display text files, images, or let users download files by adding the right checks and headers. Always check if the file exists before reading it, and set the correct headers based on whether you want to show the file or make it download.