Home > Bash, Linux, Programmering > Executing a Shell Command Using PHP

Executing a Shell Command Using PHP

January 30th, 2011 Leave a comment Go to comments

You can use either system() or exec(). Just remember to ALWAYS use the full path to the command. So instead of entering ‘top -n1’ use ‘/usr/bin/top -n1’. So may also need to provide additional paramater to the command so it will run correctly as a background process. Using ‘top’ command as example again you need to add the ‘-b’ parameter to make it run correctly like this ‘/usr/bin/top -b -n1’

When you use system() it will print all the command output to the browser. If you simply want to execute a command and you don’t want the result to be displayed just redirect the output to some file like this :

system(‘/usr/bin/top -b -n1 > /dev/null 2>&1’)

If you want to get the output (for further processing etc) use exec(). For example :

exec(‘/usr/bin/top -b -n1’, $result)

$result will become an array containing every line of output from the ‘top’ command.

Categories: Bash, Linux, Programmering Tags:
  1. No comments yet.
  1. No trackbacks yet.