Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page