How to Read a File in PHP: Simple Guide with Examples
In PHP, you can read a file easily using the
file_get_contents() function which reads the entire file into a string. Alternatively, use fopen() with fread() to read files in smaller parts for more control.Syntax
file_get_contents() reads the whole file at once and returns its content as a string.
fopen() opens a file and returns a handle. You then use fread() to read from this handle, and fclose() to close the file.
php
<?php // Using file_get_contents $content = file_get_contents('filename.txt'); // Using fopen and fread $handle = fopen('filename.txt', 'r'); $content = fread($handle, filesize('filename.txt')); fclose($handle); ?>
Example
This example shows how to read a file named example.txt using file_get_contents() and print its content.
php
<?php // Read the whole file content $content = file_get_contents('example.txt'); echo $content; ?>
Output
Hello, this is a sample file.
It has multiple lines.
Enjoy reading!
Common Pitfalls
- Trying to read a file that does not exist causes warnings or errors.
- Not checking if
file_get_contents()orfopen()succeeded before reading. - For large files, reading the entire file at once may use too much memory.
Always check if the file exists and handle errors gracefully.
php
<?php // Wrong way: no error check $content = file_get_contents('missing.txt'); echo $content; // Right way: check if file exists if (file_exists('missing.txt')) { $content = file_get_contents('missing.txt'); echo $content; } else { echo 'File not found.'; } ?>
Output
File not found.
Quick Reference
| Function | Purpose | Notes |
|---|---|---|
| file_get_contents() | Reads entire file into a string | Simple and fast for small files |
| fopen() | Opens a file handle | Use with fread() and fclose() |
| fread() | Reads from an open file handle | Specify number of bytes to read |
| fclose() | Closes an open file handle | Always close to free resources |
| file_exists() | Checks if a file exists | Use before reading to avoid errors |
Key Takeaways
Use file_get_contents() for quick and easy file reading in PHP.
For large files, use fopen() with fread() to read in parts and save memory.
Always check if the file exists before trying to read it to avoid errors.
Close file handles with fclose() after reading to free system resources.
Handle errors gracefully to make your code more reliable.