Back to results for “File System”
PHP › File Handling & File System Functions

How do you read the contents of a file in PHP using functions like file_get_contents and fopen?

Beginner

Answer

file_get_contents provides a simple, convenient way to read an entire file's contents into a single string in one function call, which is perfect for smaller files, while fopen opens a file and returns a file handle that you can then read from incrementally using functions like fgets or fread, which is more appropriate for very large files where loading the entire content into memory at once would be impractical.
$content = file_get_contents('data.txt');

$handle = fopen('largefile.txt', 'r');
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);
Real-world example A configuration loader uses file_get_contents to quickly read a small settings file into memory, while a log analysis tool uses fopen and fgets to process a massive multi gigabyte log file line by line without exhausting available memory.

Common follow-ups: What is the memory difference between file_get_contents and reading a file line by line?;What happens if you forget to close a file handle after opening it?