0

I have this

public function memory()
{
    $result = [];
    $result['total'] = shell_exec(`free -m | grep Mem: | awk '{ print $2 }'`);
    $result['used'] = shell_exec(`free -m | grep Mem: | awk '{ print $3 }'`);
    $result['free'] = shell_exec(`free -m | grep Mem: | awk '{ print $4 }'`);

    return $result;

}

I am trying to create access my memory of my Ubuntu VM, and graph it.

But API keep return null.

{
total: null,
used: null,
free: null
}

If I run directly in the VM - I got it.

└── free -m
             total       used       free     shared    buffers     cached
Mem:          2002       1244        757         63        159        427
-/+ buffers/cache:        657       1344
Swap:            0          0          0
┌──[john@server]──[/server] 
└── free -m | grep Mem:
Mem:          2002       1244        757         63        159        427                  
┌──[john@server]──[/server] 
└── free -m | grep Mem: | awk '{ print $2 }'                                                
2002
You have new mail in /var/mail/john
┌──[john@server]──[/server] 
└── free -m | grep Mem: | awk '{ print $3 }'                                                
1243
┌──[john@server]──[/server] 
└── free -m | grep Mem: | awk '{ print $4 }'                                                
757

Did I do anything wrong in the way I write my function?

Am I used shell_exec() wrong?

Please give me some suggestions.

code-8
  • 54,650
  • 106
  • 352
  • 604
  • If you're running this code on a shared hosted server, they might have blocked `shell_exec()` in PHP for security reasons. or it might be related to this question https://stackoverflow.com/questions/18241305/shell-exec-returning-null-on-ls* – N69S Sep 19 '19 at 16:04
  • 2
    You also have to remove backtick `\`` in your `shell_exec(`free -m | grep Mem: | awk '{ print $2 }'`);` which is same as `shell_exec` – LF00 Sep 19 '19 at 16:27
  • @KrisRoofe good to know. Thanks. – code-8 Sep 19 '19 at 16:32
  • Like already mentioned it might be related to permissions. When run from PHP the command does not necessarily run as `john`. For example, if it's executed via a website the user will be `www-data` – Tox Sep 19 '19 at 17:17

0 Answers0