Name

exec()

Synopsis

    string exec ( string command [, array &output [, int &return_val]] )

The exec() function runs an external program, specified in the first parameter. It sends back the last line outputted from that program as its return value, unlike passthru(), which prints out all the output the program generates.

    print exec("uptime");

The uptime command is available on most Unix systems and prints out just one line of output—perfect for exec().

Calling exec() is usually preferred when the output of your program is irrelevant, whereas passthru() automatically prints your output.

If you pass a second and third parameter to exec(), the output of the command will be put into parameter two as an array with one line per element, and the numeric exit status of the command will be put into parameter three. Similarly, if you pass a second parameter to passthru(), it will be filled with the return value of the command.

For example:

    exec("dir", $output, $return);
    echo "Dir returned $return, and output:\n";
    var_dump($output);

That example should work fine on Windows, as well as on many versions of Unix.

Tip

PHP's exec() is more like the Perl execution operator ('...') than the Perl exec() function.

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.