DEV Community

ライフポータル
ライフポータル

Posted on • Originally published at code-izumi.com

PHP Memory Management: How to Monitor Usage, Peaks, and Limits

When processing large datasets or running long-running batch scripts in PHP, you may encounter the dreaded error: "Fatal error: Allowed memory size of... exhausted".

To maintain application performance and prevent unexpected crashes, it is essential to accurately monitor how much memory your script is consuming. In this guide, we’ll explain how to use built-in functions like memory_get_usage(), how to format the output into human-readable units (MB/KB), and how to adjust memory limits (memory_limit) to suit your environment.


1. Checking Current Usage: memory_get_usage()

To find out the "instantaneous" memory consumption at any point in your script, use memory_get_usage(). This function returns the amount of memory allocated to the script in bytes (int).

Basic Usage and Real Memory

Running the function without arguments returns the memory currently used by the PHP memory manager. By passing true as the first argument, you can get the total memory actually allocated from the system (OS).

<?php
// Memory before creating an array
echo "Initial: " . number_format(memory_get_usage()) . " bytes\n";

// Consume memory by creating a large array
$array = range(1, 100000);

// Memory after creation
echo "After Array: " . number_format(memory_get_usage()) . " bytes\n";

// Total memory allocated from the system
echo "Real Memory: " . number_format(memory_get_usage(true)) . " bytes\n";
?>
Enter fullscreen mode Exit fullscreen mode

Why check real memory?
The value returned by memory_get_usage(true) is often larger than the actual usage because PHP allocates memory in chunks. Checking this value is helpful when designing server resource requirements.


2. Checking Peak Usage: memory_get_peak_usage()

A script might crash not because its average usage is high, but because it hit a peak limit for a split second. To find the highest memory point reached during script execution, use memory_get_peak_usage().

<?php
$data = [];
for ($i = 0; $i < 50000; $i++) {
    $data[] = md5($i);
}

// Release memory
unset($data);

echo "Current: " . number_format(memory_get_usage()) . " bytes\n";
echo "Peak: " . number_format(memory_get_peak_usage()) . " bytes\n";
?>
Enter fullscreen mode Exit fullscreen mode

Even if you use unset() to free up memory later, memory_get_peak_usage() will remember the maximum point reached. This is critical for troubleshooting memory-intensive batch processes.


3. Formatting Bytes to Human-Readable Units

Since these functions return raw bytes, the numbers can get very long. It's much easier to read "12 MB" than "12582912 bytes." Here is a standard helper function to format the output:

<?php
/**
 * Formats bytes into KB, MB, GB, etc.
 */
function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];

    if ($bytes <= 0) return '0 B';

    $pow = floor(log($bytes) / log(1024));
    $unit = isset($units[$pow]) ? $units[$pow] : 'TB';

    // Convert bytes using bit shifting (1024^pow)
    $bytes /= (1 << (10 * $pow));

    return round($bytes, $precision) . ' ' . $unit;
}

echo "Current Usage: " . formatBytes(memory_get_usage()) . "\n";
echo "Peak Usage: " . formatBytes(memory_get_peak_usage()) . "\n";
?>
Enter fullscreen mode Exit fullscreen mode

4. Managing the memory_limit

PHP has a built-in safety cap for how much memory a single script can use.

Checking the Current Limit

You can retrieve the memory_limit value defined in your php.ini using ini_get():

<?php
echo "Current Limit: " . ini_get('memory_limit'); // e.g., "128M"
?>
Enter fullscreen mode Exit fullscreen mode

Temporarily Increasing the Limit

If you have a specific heavy task, you can override the limit for that script's duration using ini_set().

<?php
// Increase limit to 512MB
ini_set('memory_limit', '512M');

// Set to unlimited (use with extreme caution)
// ini_set('memory_limit', '-1');
Enter fullscreen mode Exit fullscreen mode

5. Tips for Reducing Memory Consumption

Monitoring is the first step, but writing memory-efficient code is the ultimate goal.

  • Use unset(): Manually destroy large arrays or objects once they are no longer needed.
  • Avoid fetchAll() for Large Queries: When fetching thousands of rows from a database, don't load them all into an array at once. Use fetch() row-by-row or use Generators (yield).
  • Chunking Data: In frameworks like Laravel, use methods like chunk() or cursor() to load only a subset of data into memory at a time.

Conclusion

Effective memory management in PHP is about knowing your peaks, not just your averages. By integrating memory_get_peak_usage() into your logging and using ini_set judiciously, you can build robust applications that scale without crashing.


Originally published at: [https://code-izumi.com/php/check-memory-usage/]

Top comments (0)