I needed to find the disk spaced used by members of a website yesterday. Each member’s files are in a separate directory (or folder), so I basically needed to check the size of each file in each member’s folder and add them up to see if they were over their limit. Here’s how I did it:
function getSpaceUsed()
{
$directory ='pathToDirectory/';
$total = 0;
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$total += filesize($directory.'/'.$file);
}
}
closedir($handle);
}
return round(($total/1024)/1024, 2);
}
I’m ignoring the hidden directories – ‘.’ and ‘..’ – inside the directory.
I want the answer in Megabytes. The php filesize function gives me bytes, so I’m dividing by 1024 to get KB and then 1024 again to get MB. I could do this all at once instead of dividing twice, but I think it makes it clearer as to what I’m doing – and will make it a tad bit easier if I want to change that to KB instead of MB later.
The ’round’ function will round my total to two decimal places.
Now, I can just test the results from the function against the limit I want to put on each member to see if they have exceeded their limit.
———–
Do you have a question about web development or building your website? Just Ask!!