PHP offers both simple one-liner functions and lower-level file handle functions for reading files.
file_get_contents() reads the entire file into a string — perfect for small-to-medium files.
file() reads the file into an array of lines.
fopen() + fread() / fgets() give you fine-grained control for large files.
Always close file handles with fclose() and handle errors gracefully.
Example
<?php
$path = '/var/data/config.txt';
// Read entire file as a string
if (file_exists($path)) {
$contents = file_get_contents($path);
echo $contents;
}
// Read into an array of lines (FILE_IGNORE_NEW_LINES strips
)
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
echo trim($line) . "
";
}
// Low-level fopen for large files (read line by line)
$handle = fopen($path, 'r');
if ($handle === false) {
throw new RuntimeException("Cannot open file: $path");
}
try {
while (($line = fgets($handle)) !== false) {
echo trim($line) . "
";
}
} finally {
fclose($handle);
}
// Read a specific number of bytes
$handle = fopen($path, 'r');
$chunk = fread($handle, 1024); // read first 1 KB
fclose($handle);
// Read remote URL (if allow_url_fopen is enabled)
$html = file_get_contents('https://example.com');
Pro Tip
Tip: Use file_get_contents() for most cases — it is simpler and just as fast for files under a few megabytes. Switch to fgets() in a loop only when you need to process a file line-by-line without loading it all into memory at once.