user3329720
user3329720

Reputation: 1

Adding numbers and getting a percentage

I have a PHP script that runs a few du commands to extract the kB size of 3 specific directories. That works, and I have $dir1size as 521046477, dir2size as 521043911 and $dir3size as 67167152. These pop out fine (ie no dodgy characters in the strings) if I echo the results into a JSON format. I then want to add them up to get $tot and divide by the disk size which is $disksize to get $pctused. The code I have is...

$rtn = array();
# Get disk size
$cmd = "df | sed -n '/DataVolume/s/ \+/ /gp' | cut -d' ' -f 2";
exec($cmd, $disksize, $int);
$rtn["disk"]["kB"]["total"] = $disksize[0];

# Get dir1 size
$cmd = "du --apparent-size .. | sed -n 's/[\ ]*\.\.\/TNFrontCam1$/ TNFront/p' | cut -d' ' -f 1";
exec($cmd, $dir1size, $int);
$rtn["disk"]["kB"]["TNFront"] = $dir1size[0];
# 2 more blocks like that for the other 2 directories

# Do the calulations
$tot = $dir1size + $dir2size + $dir3size;
$rtn["disk"]["kB"]["used"] = $tot;
$pctused = ($tot / $disksize) * 100; 
$rtn["disk"]["percent"]["used"] = $pctused;
$rtn["disk"]["percent"]["free"] = 100 - $pctused;

echo json_encode($rtn, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);

When I run this get Fatal Error: Unsupported operand types in the line calculating the percentage used. If I comment out the 3 percentage lines I get the JSON string but instead of showing me the sum of the 3, I just get $dir1size but in square brackets! (hence the fatal error when it tries to do the percent calcs). I've also tried intval($dirxsize) but then I get a null in the JSON output.

(I should add I am running this on a WD NAS drive that I've SSHed into in the hope that I can report usage info to my Home Assistant)

Edit - When I use PHP Sandbox, the maths all works out fine!

Upvotes: 0

Views: 52

Answers (1)

Daniels118
Daniels118

Reputation: 1227

The second parameter of the exec function is an array (one element for each line of output), so if the size is on the first line you have to access the element at index zero, like:

$disksize[0]

For every variable used as the second argument of exec:

$tot = $dir1size[0] + $dir2size[0] + $dir3size[0];
$rtn["disk"]["kB"]["used"] = $tot;
$pctused = ($tot / $disksize[0]) * 100;  

Upvotes: 1

Related Questions