PHP command line tools shell_exec, exec, PassThru, System detailed introduction _php Tips

Source: Internet
Author: User
Tags php script perl script rsync
All of these commands derive a subprocess to run the command or script that you specify, and each subprocess catches them when the command output is written to standard output (stdout).

shell_exec ()

The shell_exec () command line is actually only a variant of the reverse-apostrophe (') operator. If you have written a shell or Perl script, you know that you can capture the output of other commands within the reverse-apostrophe operator. For example, listing 1 shows how to use the reverse apostrophe to get a word count for each text (. txt) in the current directory.

Listing 1. Calculate the number of words using an inverse apostrophe
Copy Code code as follows:

#! /bin/sh
number_of_words= ' wc-w *.txt '
Echo $number _of_words

#result would 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. This assumes that there are some text files under the same directory.

Listing 2. Run the same command in Shell_exec ()
Copy Code code as follows:

<?php
$results = Shell_exec (' wc-w *.txt ');
Echo $results;
?>

As you can see in Figure 1, the results obtained are the same as those obtained from the shell script. This is because Shell_exec () allows you to run an external program through the shell and then return the result as a string.
Figure 1. The result of running the shell command via Shell_exec ()

Note that using the post-apostrophe operator alone will also result in the same results, as shown below.
Listing 3. Use the back-apostrophe operator only
Copy Code code as follows:

<?php
$results = ' wc-w *.txt ';
Echo $results;
?>

Listing 4 shows a simpler way to do this.
Listing 4. A simpler approach
Copy Code code as follows:

<?php
Echo ' wc-w *.txt ';
?>

It's important to know that there are a lot of things that can be done with UNIX command lines and shell scripts. For example, you can use a vertical bar to connect commands. You can even use the operator to create a shell script and invoke only the shell script (using or not using parameters as needed).

For example, if you only want to calculate the number of words in the first 5 text files in the directory, you can use the vertical bar (|) to connect the WC and head commands. In addition, you can put the output inside the pre tag so that it can be rendered more aesthetically in a Web browser, as shown below.

Listing 5. More complex shell commands
Copy Code code as follows:

<?php
$results = Shell_exec (' wc-w *.txt | head-5 ');
echo "<code lang=" php ">". $results. "</code>";
?>

Figure 2 shows the results of the script running listing 5.
Figure 2. Results from running more complex shell commands from shell_exec ()

Later in this article, you'll learn how to use PHP to pass parameters to these scripts. Now you can see it as a way to run the shell command, but remember that you can only view standard output. If there is an error in the command or script, you will not see the standard error (STDERR) unless you add it to stdout through a vertical bar.

PassThru ()

PassThru () allows you to run external programs and display the results on the screen. You do not need to use echo or return to view the results, which are displayed on the browser. You can add optional parameters, that is, a variable that holds the code returned from an external program, such as a successful 0, which provides a better mechanism for debugging.

In Listing 6, I use the passthru () command to run the word count script that runs in the previous section. As you can see, I also add a $returnval variable that contains the return code.

Listing 6. Run the word count script using the PassThru () command
Copy Code code as follows:

<?php
PassThru (' wc-w *.txt | head-5 ', $returnval);
echo "?>

Notice that I don't need to use echo to return anything. The results are displayed directly on the screen, as shown below.
Figure 3. Run the results of the PassThru () command using the return code

In Listing 7, I introduce a small error by removing the dash (-) before the 5 front of the script's head.
Listing 7. Introduce an error in the word Count script
Copy Code code as follows:

<?php
We introduce an error below (Removing-from's head command)

PassThru (' Wc-w *.txt | Head 5 ', $returnval);
echo "?>

Note that the script failed to run as expected. You get a blank screen, a horizontal line and a return value of 1, as shown in Figure 4. This return code usually indicates that some errors have occurred. Finding and fixing bugs is much easier if you can test the return code.
Figure 4. View error codes when using PassThru ()

exec ()
The EXEC () command is similar to Shell_exec (), but the difference is that it returns the last line of output and optionally populates the array with the full output and error code of the command. Listing 8 shows what happens when you run exec () without capturing the data in the data array.
Listing 8. Run exec () without capturing data in the data array
Copy Code code as follows:

<?php
$results = EXEC (' wc-w *.txt | head-5 ');
Echo $results;
#would print out just the "last line or results, i.e.:
#3847 myfile.txt
?>

To catch the result in an array, add the name of the array as the second argument to exec (). I performed this step in Listing 9 and took $data as the name of the array.
Listing 9. Capturing the results of an array of data from exec ()
Copy Code code as follows:

<?php
$results = EXEC (' wc-w *.txt | head-5 ', $data);
Print_r ($data);
#would print out the data array:
#Array ([0]=> 555 text1.txt [1] => 283 text2.txt)
?>

After capturing the results in an array, you can do some processing on each row. For example, you can divide the first space, store the separated values in a database table, or apply a specific format or tag to each row.
System ()
As shown in Listing 10, the system () command is a hybrid. 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.
list. System () command
Copy Code code as follows:

<?php
System (' wc-w *.txt | head-5 ');
#would Print out:
#123 file1.txt 332 file2.txt 444 File3.txt
#and so on
?>

Some examples
Now that you know how to use these PHP commands, you may still have some questions. For example, when should you use which command? This is entirely up to your needs.
In most cases, I use the exec () command and the data array to handle everything. or use Shell_exec () for simpler commands, especially if you don't care about the results. If you only need to return a shell script, I'll use PassThru (). Usually, I use different functions in different situations, and sometimes they can be interchangeable. It all depends on my mood and the purpose to be achieved.
Another question you might ask is, "What are their strengths?" ”。 If you don't have a clue, or if a project is good for using shell commands, but you don't know how to use them, I'm here to provide some insights.
If you are writing an application that provides a variety of backup or file transfer capabilities, you can choose to run the shell script that rsync supports using either shell_exec () or one of the other commands provided here. You can write a shell script that contains the necessary rsync commands, and then use PassThru () to execute it according to a user's command or cron job.
For example, a user who has the appropriate permissions (such as Administrator privileges) in your application 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 you want to send, and then click Submit. In this process, the form should have a PHP script that uses the return option variable to run the Rsync script via PassThru (), so you know if the problem occurs, as shown below.
Listing 11. Example PHP script running rsync script via PassThru ()
Copy Code code as follows:

<?php
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 those processes or files, you can use one of the commands summarized in this article to easily do this. For example, a simple grep command can help you find a file that matches a specific search condition. Use it with the EXEC () command to save the results in an array, which allows you to build an HTML table or form that further allows you to run other commands.
So far, I've discussed user-generated events--the user simply presses the button or clicks the link, and PHP runs the script. You can also use standalone PHP scripts with cron or other scheduling 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 run it. Why did you do that? It seems to be superfluous, isn't it? This is not the case-you need to consider that you can run the backup script through exec () or passthru () and then perform some behavior based on the return code. If an error occurs, you can log it to the error log or database, or send a warning e-mail message. If the script succeeds, you can dump the original output to the database (for example, Rsync has a verbose (verbose) pattern that is useful for subsequent diagnostics).

--------------------------------------------------------------------------------
Safety
Let's briefly discuss security here: If you accept user input and pass information to the shell, it's best to filter user input. Delete the commands and disallowed content that you think are harmful, such as sudo (run as Superuser) or RM (delete). In fact, you might not want users to send open requests, but instead let them choose from the list.
For example, if you run a transport program that accepts a list of files as a parameter, you should list all files through a series of check boxes. Users can select and deselect files and activate the rsync shell script by clicking Submit. Users cannot enter files themselves or use regular expressions.

--------------------------------------------------------------------------------
Conclusion
In this article, I demonstrated the basics of using the PHP command 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 application.

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.