简体   繁体   中英

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

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+/" .

删除空格,例如:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM