[ Team LiB ] Previous Section Next Section

Running External Commands with system() or the Backtick Operator

The system() function is similar to the exec() function in that it launches an external application. It requires the path to a command and, optionally, a variable, which is populated with the command's return value. system() prints the output of the shell command directly to the browser. The following code fragment prints the manual page for the man command itself:


<?php
print "<pre>";
system( "man man | col -b", $return );
print "</pre>";
?>

We print pre tags to the browser to maintain the formatting of the page. We use system() to call man, piping the result through another application called col, which reformats the text for viewing as ASCII. We capture the return value of our shell command in the $return variable, and system() returns its output.

You can achieve a similar result by using the backtick operator. This involves surrounding a shell command in backtick (`) characters. The enclosed command is executed and any output is returned. You can print the output or store it in a variable.

We can re-create the previous example using backticks:


print "<pre>";
print 'man man | col -b';
print "</pre>";

Note that you must explicitly print the return value from the backtick operator.

    [ Team LiB ] Previous Section Next Section