-
Hajipur, Bihar, 844101
Reading files is one of the fundamental tasks in PHP file handling. Whether you are displaying content from a text file, processing CSV data, or importing logs, understanding how to open and read files efficiently is essential.
This tutorial explains how to open files in different modes, read them fully or line by line, and handle errors gracefully, with practical examples.
When Vrinda is building a blog, she might store posts in text files. To display these posts on the website, she needs to read files efficiently. Similarly, Ananya could have a file containing a list of users, and reading the file is the first step in processing or displaying this information.
PHP provides multiple functions to read file content, including:
fopen()
– to open a file
fread()
– to read a specific number of bytes
fgets()
– to read a file line by line
file()
– to read an entire file into an array
file_get_contents()
– to read an entire file into a string
Before reading a file, you must open it using fopen()
.
<?php
$file = fopen("example.txt", "r"); // open file in read-only mode
if ($file) {
echo "File opened successfully.";
} else {
echo "Unable to open file.";
}
?>
"r"
mode opens the file for reading only.
If the file does not exist, PHP will return false.
Tip: Always check whether the file opened successfully to prevent errors.
The fread()
function allows you to read a specific number of bytes from a file.
<?php
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt")); // read full file
fclose($file);
echo $content;
?>
filesize()
determines how many bytes to read.
Closing the file with fclose()
frees up server resources.
If Riya writes a poem in example.txt
, this code will read and display the entire poem.
Sometimes, reading a file line by line is more efficient, especially for large files.
<?php
$file = fopen("data.txt", "r");
if ($file) {
while (!feof($file)) { // loop until the end of the file
$line = fgets($file); // read one line at a time
echo $line . "<br>";
}
fclose($file);
} else {
echo "Failed to open file.";
}
?>
feof()
checks whether the end of the file has been reached.
fgets()
reads the file one line at a time.
For example, Ananya could have a list of student names stored line by line in data.txt
. This loop will display each name neatly.
The file()
function reads the entire file into an array, where each line becomes an array element.
<?php
$lines = file("students.txt");
foreach ($lines as $line) {
echo $line . "<br>";
}
?>
If Vrinda has a file with project titles, each title will be stored as a separate element, making it easy to loop through and display.
The file_get_contents()
function reads an entire file into a string. It is simpler than using fopen()
and fread()
for smaller files.
<?php
$content = file_get_contents("message.txt");
echo $content;
?>
Ideal for quickly reading small text files.
Returns false if the file cannot be opened.
If Riya has a file message.txt
with a welcome note, this function will display it in one step.
Always handle errors when opening or reading files.
<?php
$file = @fopen("missing.txt", "r") or die("File not found!");
?>
The @
suppresses warnings.
die()
displays a custom error message and stops execution.
This prevents the page from crashing if a file is missing or inaccessible.
Suppose Ananya wants to display all user feedback stored in feedback.txt
.
<?php
$file = fopen("feedback.txt", "r");
if ($file) {
while (!feof($file)) {
$feedback = fgets($file);
echo "<p>$feedback</p>";
}
fclose($file);
} else {
echo "No feedback available.";
}
?>
Each line of the file represents a separate feedback entry.
Displaying it in <p>
tags improves readability on a webpage.
If Vrinda wants to know how many entries are in her file:
<?php
$lines = file("feedback.txt");
echo "There are " . count($lines) . " feedback entries.";
?>
This method is efficient and easy to implement for small to medium-sized files.
Always close files using fclose()
after reading.
Check if files exist with file_exists()
before opening.
Handle large files line by line with fgets()
to avoid memory overload.
Use proper permissions to ensure files are readable but secure.
Sanitize output if the file contains user-submitted content to prevent XSS attacks.
PHP makes reading files straightforward with multiple options:
fopen()
and fread()
for full control over file reading
fgets()
to read line by line
file()
to read into an array
file_get_contents()
to read the whole file as a string
Whether you’re displaying text, logs, or user data, these functions let you read and process files efficiently and securely.
Open a file named example.txt
in read mode and display its full content.
Read a file line by line using fgets()
and display each line on a new HTML line.
Use file_get_contents()
to read the entire content of message.txt
and echo it.
Read a file into an array using file()
and loop through it to display each element.
Check if a file named data.txt
exists before attempting to open it.
Handle errors gracefully when opening a file that may not exist using @fopen()
and die()
.
Count the number of lines in a file named feedback.txt
and display the count.
Display all user feedback from feedback.txt
, with each feedback entry inside a <p>
tag.
Read a large file line by line and stop reading after 10 lines.
Open a file, read its content, and then close it using fclose()
to free server resources.