PHP Read File – Step-by-Step Guide
Basic PHP File Reading Methods
PHP provides several functions to read files:
fread()
fgets()
file_get_contents()
readfile()
Reading the Entire File with file_get_contents()
$content = file_get_contents("example.txt");
echo $content;
✅ Reads the entire file as a string.
✅ Simple and efficient for small files.
✅ Returns false
on failure.
Reading a File Line by Line with fgets()
$file = fopen("example.txt", "r");
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
} else {
echo "Error opening the file.";
}
✅ Reads one line at a time.
✅ Suitable for large files.
Reading File in Chunks with fread()
$file = fopen("example.txt", "r");
if ($file) {
$content = fread($file, filesize("example.txt"));
echo $content;
fclose($file);
} else {
echo "Error opening the file.";
}
✅ Reads a specific number of bytes.
✅ Useful for binary files.
Using readfile() to Output File Contents
readfile("example.txt");
✅ Outputs the file directly to the browser.
✅ Returns the number of bytes read.
Handling File Errors
$file = "nonexistent.txt";
if (file_exists($file)) {
echo file_get_contents($file);
} else {
echo "File does not exist.";
}
Best Practices for PHP File Reading
🔒 Check if the file exists before reading.
🔒 Close the file after reading to free up resources.
🔒 Handle errors gracefully.
Complete PHP File Reading Code
$file = "example.txt";
if (file_exists($file)) {
$handle = fopen($file, "r");
while (($line = fgets($handle)) !== false) {
echo htmlspecialchars($line) . "<br>";
}
fclose($handle);
} else {
echo "File not found.";
}