Приглашаем посетить
Герцен (gertsen.lit-info.ru)

13.11 Running Shell Commands

Previous Table of Contents Next

13.11 Running Shell Commands

While you can do almost anything in PHP, you can't do everything. If you need to run an external program from inside a PHP script, you have a few options. These are described in the "Program Execution" section of the PHP Manual (http://www.php.net/exec). Example 13-14 demonstrates the shell_exec( ) command, which runs a program and returns its output. In Example 13-14, shell_exec( ) runs the df command, which (on Unix) produces information about disk usage.

Example 13-14. Running a program with shell_exec( )
// Run "df" and divide up its output into individual lines

$df_output = shell_exec('/bin/df -h');

$df_lines = explode("\n", $df_output);



// Loop through each line. Skip the first line, which

// is just a header

for ($i = 1, $lines = count($df_lines); $i < $lines; $i++) {

    if (trim($df_lines[$i])) {

        // Divide up the line into fields

        $fields = preg_split('/\s+/', $df_lines[$i]);

        // Print info about each filesystem

        print "Filesystem $fields[5] is $fields[4] full.\n";

    }

}

Example 13-14 prints something like this:

Filesystem / is 63% full.

Filesystem /boot is 7% full.

Filesystem /opt is 93% full.

Filesystem /dev/shm is 0% full.

Just like when using external input in a SQL query or filename, you need to be careful when using external input as part of an external command line. Make your programs more secure by using escapeshellargs( ) to escape shell metacharacters in command-line arguments.

Read more about running external commands in Section 12.7 of Programming PHP (O'Reilly) and in PHP Cookbook (O'Reilly), Recipes 18.20, 18.21, 18.22 and 18.23.

    Previous Table of Contents Next