I used file_get_contents for everything until a log file grew past my memory_limit and the script died with ‘Allowed memory size exhausted’.
It wasn’t a complex issue. It was a five-line script that read a log, parsed it, and wrote a summary. The log was a little over 2GB. That’s not huge in disk terms, but for a single string in PHP memory, it’s enough to choke a standard configuration.
I stopped using file_get_contents as my default after that. Now I pick the tool based on size.
file_get_contents is fine for small files
There is no shame in using file_get_contents. It is readable, it is one line, and it works.
If you are reading a config file, a JSON response from an API, or a template string, use this. You know the file is small. You need the whole thing as a single string. This is the right tool.
$config = json_decode(file_get_contents('config.json'), true);
That’s it. No handle management, no closing resources. If the file fits comfortably in memory, don’t overcomplicate it.
I know you want to be “efficient” everywhere. But efficiency that costs readability is often a bad trade. For files under 1MB, file_get_contents is usually the best choice.
When the file gets big, stream it
The problem with file_get_contents is that it loads the entire file into memory at once. A 2GB log becomes a 2GB string. If you have other things in memory, you’re close to the limit.
For large files, or files where you don’t know the size ahead of time, use fopen and fgets. This streams line by line. Your memory footprint stays flat no matter how big the file is.
Here’s what I do:
$handle = fopen('app.log', 'r');
if ($handle === false) {
// handle error, don't proceed
return;
}
while (($line = fgets($handle)) !== false) {
// process one line at a time
// memory stays low because we only hold one line
}
fclose($handle);
The key difference: fgets reads one line, processes it, and moves to the next. The previous line is eligible for garbage collection. You never hold the whole file in memory.
Always check if fopen returns false. If the file doesn’t exist or permissions are wrong, you get false. If you don’t check, fgets will throw a TypeError and the script dies.
The modes I actually use
When I open a file, I pick a mode. Here’s what I reach for:
‘r’ : Read only. Cursor starts at the beginning.
‘w’ : Write and truncate. Careful. This wipes the file empty before you write. If you meant to append, you used the wrong mode.
‘a’ : Append. Adds data to the end. Good for logs.
‘x’ : Create and fail if it exists. I use this for lock files. It’s a simple way to ensure atomic creation.
‘c’ : Open for writing without truncating. If the file exists, the old content stays. It’s write-only. If you need to read and write, use 'c+'.
You might see ‘b’ (binary) in older code or Windows examples. It’s harmless on Linux and Mac. On Windows, it prevents newline translation. I add it when I’m dealing with binary data or when I suspect Windows-specific line ending issues. Otherwise, skip it.
SplFileObject for CSV and structured data
If you’re parsing CSV, fgets works but it’s clunky. You have to split lines manually, handle quotes, deal with newlines inside fields. It’s a pain.
PHP has SplFileObject for this. It’s the object-oriented version of file handling, and it’s genuinely better for structured data.
$file = new SplFileObject('data.csv');
$file->setFlags(
SplFileObject::READ_CSV |
SplFileObject::READ_AHEAD |
SplFileObject::SKIP_EMPTY |
SplFileObject::DROP_NEW_LINE
);
foreach ($file as $row) {
// $row is an array of fields
// no need to split by comma yourself
}
READ_CSV handles the parsing. DROP_NEW_LINE removes the trailing newline so your last field isn’t "value\n". Without READ_AHEAD and SKIP_EMPTY, the empty line at the end of the file comes back as a row containing a single null, which is a classic import bug.
I use this for any CSV import. It’s cleaner than manual parsing, and it streams row by row, so memory stays low.
Measure it
Don’t guess. Use memory_get_peak_usage(true) to see what your script actually uses.
Run your file reading code on a large file. Check the peak memory usage. Then switch from file_get_contents to fgets and run it again. You’ll see the difference.
file_get_contents grows with the file size. fgets doesn’t. That’s the whole point. If your script is dying under load, this is usually why.
I’ve done the “it should be fine” thing before. It was not fine. The log was bigger than I expected. The memory spike took out the worker process. After that, I measure.
Writing files
For simple appends, file_put_contents with flags is great:
file_put_contents('app.log', $line . "\n", FILE_APPEND | LOCK_EX);
FILE_APPEND adds to the end. LOCK_EX locks the file so two processes don’t write at the same time and corrupt the data. Use this for occasional writes, like logging an error or saving a state change.
But if you’re writing many lines in a loop, don’t call file_put_contents every iteration. That opens and closes the file each time. It’s slow.
Use fopen with 'a' mode, write all your lines, then close it:
$handle = fopen('output.txt', 'a');
if ($handle === false) {
return;
}
foreach ($lines as $line) {
fwrite($handle, $line . "\n");
}
fclose($handle);
One open, many writes, one close. Much faster than reopening the file for every line.
My rule
I stopped overthinking this. Here’s my decision tree:
Small and I need all of it? Use file_get_contents. Config files, JSON, templates, small text files. Keep it simple.
Big or unknown size? Use fgets in a loop. Logs, large data dumps, anything where memory matters.
CSV? Use SplFileObject with READ_CSV. It handles the parsing for you and streams properly.
That’s it. No more “which is faster” debates. The speed doesn’t matter as much as whether the whole file needs to be in memory. If it does, use file_get_contents. If it doesn’t, stream it.
The function isn’t the point
I used to think fopen was “better” because it was lower level. I thought file_get_contents was “lazy.” Neither is true.
The question isn’t which function is faster or more elegant. The question is: does this file need to be entirely in memory?
If yes, file_get_contents is the right tool. It’s readable, it’s simple, and it works.
If no, you need to stream. fgets or SplFileObject. Pick the one that fits your data format.
That’s the whole lesson. Stop guessing file sizes. Check your memory usage. Pick the tool that matches the job.