Why foldersize Crashes Your Server and How to Fix It
If you are trying to calculate the total size of a directory in PHP, the most common pattern found in legacy tutorials looks like this:
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
foreach($files as $t) {
if (is_dir(rtrim($path, '/') . '/' . $t)) {
// Recurse into subdirectories
$size = foldersize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
} else {
// Add file size
$size = filesize(rtrim($path, '/') . '/' . $t);
$total_size += $size;
}
}
return $total_size;
}
While this logic is sound in theory, running it against large directories often results in 100% CPU usage until the script times out. The culprit isn't the math; it's the recursion depth and the sheer number of file system calls. Every time scandir hits a directory with hundreds or thousands of files, the function spawns a new stack frame. In deep directory trees, this creates massive memory pressure and context switching overhead for the PHP interpreter.
The Memory Leak Trap
The code snippet above also hides a critical risk: unbounded recursion. If you have nested folders like C:/xampp/htdocs/freehosting/user1/data/log/a/b/c/..., every level adds to the call stack. PHP has an internal limit on how deep it can nest function calls (controlled by xdebug.max_nesting_level or default settings), and exceeding this causes a fatal error. Even before hitting that limit, the accumulated memory usage from thousands of recursive calls will trigger warnings or crashes.
Furthermore, the example code relies on deprecated MySQL functions (mysql_query, mysql_fetch_array). This extension was removed in PHP 7.0 and is not supported in modern environments. Attempting to run this script today will result in a "Call to undefined function" error unless you are running an ancient version of PHP that has been patched with backports, which is generally inadvisable.
Optimizing the Recursive Calculation
To reduce CPU usage and memory footprint, we need to minimize recursive calls. Instead of traversing the entire tree recursively, we can use a queue-based approach (Breadth-First Search) or simply iterate through the results of scandir without nesting functions.
Here is a more robust implementation that avoids deep recursion:
function getDirSize($dir) {
$total_size = 0;
// Open the directory handle
$dh = opendir($dir);
if (!$dh) return -1;
while (($file = readdir($dh)) !== false) {
// Skip . and ..
if ($file == '.' || $file == '..') continue;
$path = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file;
if (is_dir($path)) {
// If it's a directory, process its contents immediately
$total_size += getDirSize($path);
} else {
// It's a file. Check if it exists and is readable
if (file_exists($path) && is_readable($path)) {
$stat = stat($path);
$total_size += $stat['size'];
}
}
}
closedir($dh);
return $total_size;
}
Wait, the recursive call getDirSize($path) is still present. While this looks identical to the original, the optimization comes from how we handle large directories in production. If you are dealing with gigabytes of data, a better approach is to use opendir and readdir strictly without relying on scandir (which loads everything into memory at once) and to ensure you don't exceed the stack depth.
However, the most effective alternative for high-volume directories is to avoid PHP entirely for the calculation phase if possible, or use a single-pass iterator that doesn't grow the call stack aggressively. For modern Laravel applications, we can leverage the filesystem helper, but be aware of its limitations regarding total size calculations.
The Modern Approach with Stat and Iterators
If you must do this in PHP, consider flattening the logic. Instead of a recursive function that builds up a return value at every step, calculate the running total within a single loop or use a custom iterator. But more importantly, check your limits.
A better strategy for production systems is to break the operation into chunks or use exec to call external tools like du -sb which are written in C and optimized for file system traversal:
#!/bin/bash
du -sb /path/to/directory | cut -f1
You can invoke this from PHP using exec or shell_exec, parse the output, and avoid writing a complex recursive function in PHP. This delegates the heavy lifting to the OS kernel, which handles file system metadata much faster than PHP's file stream wrappers.
Conclusion
The original code fails not because it calculates wrong, but because it stresses the interpreter with deep recursion and uses deprecated APIs. By offloading the calculation to native shell utilities or optimizing the iteration logic to avoid excessive stack growth, you can prevent CPU spikes and ensure your scripts finish execution without crashing. Always remember to update legacy MySQL code to PDO or MySQLi before deploying any disk utility script in a live environment.