PHP: memory errors

spO0q 🐒🎃 - May 24 '23 - - Dev Community

PHP is beginner-friendly and abstracts complex mechanisms, so you don't have to handle it by yourself.

It's pretty convenient, but, as a beginner, you might encounter errors that are difficult to solve. Memory errors can be tough, indeed, and you won't like the following message:

Fatal error: Allowed memory size of [...]

While this error can trigger for various reasons, here are the most common ones and how you can solve the problem.

I/O: Loading large files

If you use built-in helpers like file_get_contents() to read/write/search in small files, you might get what you want without raising any error.

It's another story with large files. The server will likely limit memory usage, and even if it doesn't, that's not unlimited.

You may try to increase this limit, but that's not the best approach. Don't get me wrong. Sometimes, you do have to increase that limit, but PHP provides I/O streams to run common operations on large files.

fopen or fgets are low-level PHP helpers you can use to fix the problem. Instead of loading the entire file into memory, the data will come in chunks.

It keeps the memory footprint low and "in control."

The bad loops

PHP provides convenient keywords, like while, for or foreach, but, in practice, it's not uncommon to see bad implementations.

Here are typical situations:

  • you're trying to loop over an array that is too big
  • you're nesting loops
  • you have an infinite loop
  • you're running a CLI script that exhausts your server

And here are a few alternatives:

  • read about generators and iterable
  • read about recursion
  • use frameworks to handle large collections or big maths
  • split data to process it in chunks

Of course, it does not mean you have to use one of the above approaches for every loop you create, but, in my experience, the problem is usually the code, not the server capacity.

Memory leaks

Leaks happen when your code keeps using memory when it is no longer needed.

While PHP has some garbage collection, it does not cover all cases, which sometimes impacts performance significantly.

It's usually difficult to spot, so you'll likely need to scan you app with various tools.

How to prevent and fix most memory errors

The best way, to me, is to profile your app:

  • use xdebug
  • use Xhprof
  • use memprof
  • use built-in PHP helpers, like memory_get_peak_usage(), memory_get_usage()

PHP 8 introduced WeakMaps recently. While it won't be the ultimate solution to all memory issues, it might help garbage collect unused objects that are not unset automatically.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .