PHP command line tool shell_exec, exec, passthru, detailed usage of system

Source: Internet
Author: User
Tags call shell
PHP provides a large number of functions for executing external commands, including shell_exec (), exec (), passthru (), and system (). These commands are similar, but provide different interfaces for the external programs you run. All these commands are derived from a sub-process used to run your specified commands or scripts, and each sub-process will capture them when the command output is written to the standard output (stdout.

Shell_exec ()

The shell_exec () command line is actually only a variant of the anti-apostrophes (') operator. If you have written shell or Perl scripts, you can capture the output of other commands in the anti-float operator. For example, listing 1 shows how to use the extension number to count the words in each vertex (.txt) in the current directory.

List 1. calculate the number of words using the anti-marker

The code is as follows:


#! /Bin/sh
Number_of_words = 'WC-w *. txt'
Echo $ number_of_words

# Result wocould be something like:
#165 readme.txt 388 results.txt 588 summary.txt
# And so on ....


In your PHP script, you can run this simple command in shell_exec (), as shown in listing 2, and get the desired result. Suppose there are some text files in the same directory.

Listing 2. run the same command in shell_exec ()

The code is as follows:


$ Results = shell_exec ('WC-w *. txt ');
Echo $ results;
?>


As shown in Figure 1, the results are the same as those obtained from the shell script. This is because shell_exec () allows you to run external programs through shell and then return results in the form of strings.
Figure 1. result of running shell command through shell_exec ()

Note that only the suffix marker operator will get the same result, as shown below.
Listing 3. only use the suffix marker operator

The code is as follows:


$ Results = 'WC-w *. txt ';
Echo $ results;
?>


Listing 4 provides a simpler method.
Listing 4. simpler methods

The code is as follows:


Echo 'WC-w *. txt ';
?>


It is important to know that many things can be done through UNIX command lines and shell scripts. For example, you can use a vertical line to connect commands. You can even use operators to create shell scripts in them and only call shell scripts (use or not use parameters as needed ).

For example, if you only want to calculate the number of words in the first five text files in the directory, you can use a vertical line (|) to connect the wc and head commands. In addition, you can place the output result in the pre tag so that it can be visually displayed in a Web browser, as shown below.

Listing 5. more complex shell commands

The code is as follows:


$ Results = shell_exec ('WC-w *. txt | head-5 ');
Echo"".$results . "";
?>


Figure 2 demonstrates the result of running the script in listing 5.
Figure 2. result of running more complex shell commands from shell_exec ()

Later in this article, you will learn how to use PHP to pass parameters for these scripts. Now you can think of it as a way to run shell commands, but remember that you can only see standard output. If a command or script has an error, you will not see the standard error (stderr) unless you add it to stdout through a vertical line.

Passthru ()

Passthru () allows you to run external programs and display results on the screen. You do not need to use echo or return to view the results; they are displayed in the browser. You can add an optional parameter, that is, the variable that saves the code returned from an external program, for example, 0 indicating success, which provides a better mechanism for debugging.

In listing 6, I run the word count script in the previous section using the passthru () command. As you can see, I also add a $ returnval variable containing the returned code.

Listing 6. run the word count script using the passthru () command

The code is as follows:


Passthru ('WC-w *. txt | head-5', $ returnval );
Echo"

". $ Returnval;
?>


Note: I don't need to use echo to return anything. The result is displayed directly on the screen, as shown below.
Figure 3. result of executing the passthru () command using the return code

In listing 7, I introduced a small error by deleting the hyphen (-) before 5 in the script header.
Listing 7. introduce an error in the word count script

The code is as follows:


// We introduce an error below (removing-from the head command)

Passthru ('WC-w *. txt | head 5', $ returnval );
Echo"

". $ Returnval;
?>


Note that the script fails to run as expected. What you get is a blank screen, a horizontal line and return values 1, 4. The returned code usually indicates that some errors have occurred. If you can test the returned code, it is much easier to find and fix errors.
Figure 4. View error code when passthru () is used

Exec ()
The exec () command is similar to the shell_exec () command. The difference is that it returns the last line of the output, and can be used to populate the array with the complete output and error code of the command. Listing 8 shows what happens when running exec () without capturing data in the data array.
Listing 8. run exec () without capturing data in the data array

The code is as follows:


$ Results = exec ('WC-w *. txt | head-5 ');
Echo $ results;
# Wocould print out just the last line or results, I. e .:
#3847 myfile.txt
?>


To capture the results in the array, add the name of the array to exec () as the second parameter (). I performed this step in listing 9 and named $ data as an array.
Listing 9. capture the results of the data array from exec ()

The code is as follows:


$ Results = exec ('WC-w *. txt | head-5', $ data );
Print_r ($ data );
# Wocould print out the data array:
# Array ([0] = & gt; 555 text1.txt [1] = & gt; 283 text2.txt)
?>


After capturing the results in an array, you can process each row. For example, you can divide at the first space, store the separated values in the database table, or apply a specific format or tag to each row.
System ()
As shown in listing 10, the system () command is a mixture. It directly outputs anything received from an external program like passthru. It also returns the last line like exec () and makes the return code available.
Listing 10. system () command

The code is as follows:


System ('WC-w *. txt | head-5 ');
# Wocould print out:
#123 file1.txt 332 file2.txt 444 file3.txt
# And so on
?>


Examples
Now you know how to use these PHP commands, but you may still have some questions. For example, when should I use this command? This is entirely determined by your needs.
In most cases, I use the exec () command and data array to process everything. Or use shell_exec () for simpler commands, especially when you don't care about the results. If you only need to return a shell script, I will use passthru (). Generally, I use different functions in different occasions, and sometimes they can be exchanged. It depends entirely on my mood and purpose.
Another question you may ask is "what are their strengths ?". If you have no idea, or a project is very suitable for using shell commands, but you do not know how to use them, I will provide some insights here.
If you are writing an application that provides various backup or file transfer functions, you can choose to use shell_exec () or one of the other commands provided here to run shell scripts supported by rsync. You can write shell scripts to include necessary rsync commands, and then execute passthru () based on your commands or cron jobs.
For example, if a user has proper permissions (such as administrator permissions) in your application, he wants to send 50 PDF files from one server to another. Then, the user needs to navigate to the correct location in the application, click Transfer, select the PDF to be sent, and then click Submit. In this process, the form should have a PHP script, which uses the return option variable to run the rsync script through passthru (), so that you know whether a problem occurs, as shown below.
Listing 11. example PHP script for running rsync script through passthru ()

The code is as follows:


Passthru ('xfer _ rsync. sh', $ returnvalue );
If ($ returnvalue! = 0 ){
// We have a problem!
// Add error code here
} Else {
// We are okay
// Redirect to some other page
}
?>


If your application needs to list processes or files, or data about these processes or files, you can use one of the commands summarized in this article to easily achieve this purpose. For example, a simple grep command can help you find a file that matches a specific search condition. It can be used with the exec () command to save the results to an array, which allows you to build an HTML table or form, and further allows you to run other commands.
So far, I have discussed user-generated events. users only need to press the button or click the link, and PHP will run the corresponding script. You can also use an independent PHP script with cron or other calendar programs to achieve some interesting results. For example, if you have a backup script, you can run it through cron or package it into a PHP script and then run it. Why? This seems redundant, isn't it? This is not the case -- you need to consider this. you can run the backup script through exec () or passthru () and then execute some actions based on the returned code. If an error occurs, you can record it in the error log or database, or send a warning email. If the script is successful, you can dump the original output to the database (for example, rsync has a detailed (verbose) mode, which is useful for subsequent troubleshooting ).

--------------------------------------------------------------------------------
Security
Here we will briefly discuss security: If you accept user input and pass the information to the shell, it is best to filter user input. Delete commands and contents that you think are harmful, such as sudo (run as a super user) or rm (delete ). In fact, you may not want users to send open requests, but ask them to select from the list.
For example, if you run a transfer program that accepts the file list as a parameter, you should use a series of check boxes to list all files. You can select and cancel a file and click Submit to activate the rsync shell script. You cannot enter files or use regular expressions.

--------------------------------------------------------------------------------
Conclusion
In this article, I demonstrated the basic knowledge of using PHP commands to run shell scripts and other commands. These PHP commands include shell_exec (), exec (), passthru (), and system (). Now, you should practice what you have learned in your own applications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.