I'm a bit confused about the memory leaks in PHP.
I've read that PHP is releasing automatically the memory used in each request thanks to the Zend Memory Manager: http://www.webreference.com/programming/php_mem/2.html
But I see a lot of people and topics (even here in SO) concerned about PHP and memory leaks.
So I feel that I'm losing something.
Is it possible to have memory leaks in PHP between different requests?
unset() does not force immediate memory freeing, and it is used to free variable usage. PHP garbage collector cleans up the unset variables. CPU cycles are not wasted. It takes time to free memory.
Memory leaks can happen in any language, including PHP. These memory leaks may happen in small increments that take time to accumulate, or in larger jumps that manifest quickly. Either way, if your app has a memory leak, sooner or later it will cause problems.
The above mentioned memory usage can be tracked using memory_get_usage(). This function returns both real and actual memory used depending on our requirement. For example: if we are looking at specific code snippets, internal memory might be relevant.
Increasing the PHP memory limit The default memory limit is 256M and this is usually more than sufficient for most needs. If you need to raise this limit, you must create a phprc file.
It is not possible to have memory leaks from PHP scripts between different requests (when using the default Apache configuration), as the variables and code used in one request are released at the end of that request and PHP's memory allocator starts afresh for the next request. Bugs in the PHP interpreter or extensions could leak memory separately, however.
A much greater problem is that Apache child processes have PHP's memory space inside them. They swell to allocate the peak memory usage of a PHP script and then maintain this memory allocation until the child process is killed (once a process has asked the kernel to allocate a portion of memory, that memory won't be released until the process dies). For a more detailed explaination of why this is a problem and how to combat it, see my answer on Server Fault.
Memory leaks in a script, where variables are not unset and the PHP garbage collector fails, are very rare - most PHP scripts run for a few hundred milliseconds, and this is not generally enough time for even a serious memory leak to manifest.
You can monitor how much memory your PHP script is using with memory_get_usage()
and memory_get_peak_usage()
- there is also a good explanation on memory usage and how to program defensively in the PHP manual.
PHP's memory management is explained in detail in this article.
edit: You can determine the compiled in modules to Apache with httpd -l
- defaults vary by OS distribution and repository configuration. There are plenty of ways to interface PHP to Apache - most detailed here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With