1

I'm trying to execute a command through PHP with shell_exec. The PHP file is hosted by Apache on my Ubuntu server.

When I run this:

echo shell_exec("ps ax | grep nginx");

Then I get to see data. But when I run another command, for example:

echo shell_exec("cat /usr/local/nginx/config/nginx.config");

Then it's not showing anything at all. But when I copy that command and paste it in my terminal, then it executes fine.

My Apache server is running as user www-data. So I edited sudoers and added this line:

www-data ALL=(ALL:ALL) ALL

I know this is a security risk, but I wanted to make sure (for now) that www-data is able to execute all commands. But, for some reason I'm still not able to execute all commands with my PHP script.

Anyone any idea what to do?

Vivendi
  • 20,047
  • 25
  • 121
  • 196

2 Answers2

0

have you read http://php.net/manual/en/function.shell-exec.php

There is quite a discussion in comments section. Top comment is:

If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg:

Won't always work: echo shell_exec("gunzip -c -t $path_to_backup_file");

Should work: echo shell_exec("gunzip -c -t $path_to_backup_file 2>&1");

In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.

  • This seems to do something, but now it outputs: `cat: /usr/local/nginx/config/nginx.config: Permission denied`. Eventhough I should have root access because of the `www-data ALL=(ALL:ALL) ALL` line in sudoers? – Vivendi Feb 20 '15 at 23:54
0

echo shell_exec("sudo cat /usr/local/nginx/config/nginx.config");

Try that.

Niloct
  • 9,491
  • 3
  • 44
  • 57