PHP memory utilization is always an issue with web applications. As of version 5.2.0 there are two useful functions available to help determine application memory usage.
The functions are memory_get_peak_usage() and memory_get_usage(). The documentation is rather sparse but the usage of the functions is simple and straightforward. The main difference between the functions is when memory usage is reported. memory_get_usage() reports usage when a script is invoked while memory_get_peak_usage() reports peak usage during execution. The latter function also accepts a boolean value to determine whether or not to calculate the overhead of the memory profiler in the total.
For the purpose of example consider the following function:
function log_mem() {
$mem_real = memory_get_peak_usage();
$script = $_SERVER['PHP_SELF'];
if(phpversion() >= 5.2.0) {
error_log("Script $script memory usage: $mem_real bytes",0);
} else {
error_log("Your PHP version does not support memory_get_peak_usage()",0);
};
};
This can be placed into an include file or into the body of a script. The function call that does the work is then placed at the end of the script being profiled:
log_mem();
Profiling information is then logged to the error_log for the domain.
A more in depth discussion of these functions can be found at the IBM Developerworks website.
mod_php
If mod_php is in use, similar logging can be enabled by modifying the LogFormat Apache directive:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\ \"%{mod_php_memory_usage}n\"" php_memory_log
