PDA

View Full Version : file space script


B&T
6-3-03, 01:11 PM
See below post.

B&T
6-3-03, 03:05 PM
Found this example on phpnet, but I cannot get a value from $size when returned. I get the value in the loop (tried an echo in the loop), but not after the return. How do I make the value of the variable $size available after the function is returned (outside of the function).

function dirsize($dir) {
// calculate the size of files in $dir, (it descends recursively into other dirs)
$dh = opendir($dir);
$size = 0;
while (($file = readdir($dh)) !== false)
if ($file != "." and $file != "..") {
$path = $dir."/".$file;
if (is_dir($path))
$size += dirsize($path);
elseif (is_file($path))
$size += filesize($path);
}
closedir($dh);
return $size;
}

dirsize("./");

echo "Total directory size: $size bytes<br>";

RocketJeff
6-3-03, 03:43 PM
$size is a local variable that only exists in the function dirsize(). It returns the size, which you should be saving in a variable local to where you're using it.

replace:dirsize("./");

echo "Total directory size: $size bytes<br>"; with:$local_size = dirsize("./");

echo "Total directory size: $local_size bytes<br>";
Think of functions as 'black boxes' that are only accessable buy their interface - ignore any local variables internal to them.

B&T
6-3-03, 04:27 PM
works great and makes sense. thanks RocketJeff.