Allan Kimmer Jensen
Allan Kimmer Jensen

Reputation: 4389

Problems with output from exec in PHP

Hello I am trying to output my memory use in PHP.

My code looks like this:

exec('free -m', $out);
var_dump($out[1]);
list($mem, $total, $used, $free, $shared, $buffers, $cached) = explode(" ", $out[1]);
echo "Memory: " .$used. "/" . $total;

Now the problem is that the text prints

Memory: /

And the var_bump gives me this:

string(73) "Mem: 3024 1968 1055 0 159 608"

This string should not be (73) but (29). If I make my own array there is no problems at all:

$out = array('','Mem: 3024 2020 1003 0 121 708','');
string(29) "Mem: 3024 1968 1055 0 159 608"

Can anyone give me a solution or a next step in debugging this?

Best Regards, Allan

Upvotes: 0

Views: 419

Answers (2)

ajreal
ajreal

Reputation: 47321

Remove the spaces such as :

explode(" ", preg_replace('/\s+/', ' ', $out[1]));

Upvotes: 1

paxdiablo
paxdiablo

Reputation: 881563

When I run free -m, I actually get about 73 characters (lots of spaces in there):

Mem:          2047          0       2047          0          0          0

I think you'll find that's what's causing your empty used and total values: explode is picking up the empty strings somewhere in those spaces between Mem: and 2047.

One solution is to use preg_split with a separator of "/\s+/".

Upvotes: 1

Related Questions