Introduction:
PHP provides multiple methods to read a file’s contents. The most common is file_get_contents()
for reading the entire file into a string or fopen()
with a loop for larger files.
Example:
<?php
$filename = "example.txt";
if (file_exists($filename)) {
$contents = file_get_contents($filename);
echo "File contents: <br>" . nl2br($contents);
} else {
echo "File does not exist.";
}
?>
Explanation:
file_exists($filename)
checks if the file exists to prevent errors.file_get_contents($filename)
reads the entire file into a string.nl2br($contents)
converts newlines (\n
) in the file into HTML<br>
tags for proper display.