PHP Command line tool shell_exec, exec, PassThru, System detailed introduction _php tutorial

Source: Internet
Author: User
Tags perl script rsync
All of these commands derive a subprocess that runs the commands or scripts that you specify, and each child process captures 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 anti-apostrophe (') operator. If you have written a shell or Perl script, you know that you can capture the output of other commands inside the anti-apostrophe operator. For example, listing 1 shows how to use the backslash to get the word count for each text (. txt) in the current directory.

Listing 1. Use a backslash to calculate the number of words
Copy CodeThe code is as follows:
#! /bin/sh
number_of_words= ' wc-w *.txt '
Echo $number _of_words

#result would is 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 results you want. This assumes that there are some text files in the same directory.

Listing 2. Run the same command in Shell_exec ()
Copy CodeThe code is as follows:
$results = Shell_exec (' wc-w *.txt ');
Echo $results;
?>

As you can see 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 the shell and then return the results as strings.
Figure 1. The result of running the shell command through Shell_exec ()

Note that using the post-apostrophe operator will also get the same result, as shown below.
Listing 3. Use only the post-apostrophe operator
Copy CodeThe code is as follows:
$results = ' wc-w *.txt ';
Echo $results;
?>

Listing 4 shows a simpler approach.
Listing 4. A simpler approach
Copy CodeThe code is as follows:
Echo ' wc-w *.txt ';
?>

It is important to know that there are many things that can be done with UNIX command line 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 in it, and call only the shell script (using or not using parameters as needed).

For example, if you only want to calculate the number of words for the first 5 text files in that directory, you can use a 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 CodeThe code is as follows:
$results = Shell_exec (' wc-w *.txt | head-5 ');
echo " ".$results . "";
?>

Figure 2 illustrates the result of running the script in Listing 5.
Figure 2. Results from running more complex shell commands from shell_exec ()

Later in this article, you will learn how to use PHP to pass parameters to these scripts. You can now see it as a way to run a shell command, but remember that you only have the 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, they are displayed on the browser. You can add optional parameters, which are variables that hold the code returned from an external program, such as 0 for success, 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 with the PassThru () command
Copy CodeThe code is as follows:
PassThru (' wc-w *.txt | head-5 ', $returnval);
echo " ". $returnval;
?>

Note 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 result of the PassThru () command with the return code

In Listing 7, I introduced a small error by removing the dash (-) in front of 5 in the script header.
Listing 7. Introduce an error in the word Count script
Copy CodeThe 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 does not run as expected. What you get is a blank screen, a horizontal line and a return value of 1, 4 as shown. This return code usually indicates that some errors have occurred. Finding and fixing errors is much easier if you can test the return code.
Figure 4. Viewing error codes when using PassThru ()

exec ()
The EXEC () command is similar to Shell_exec () in 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 CodeThe code is as follows:
$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 the array, add the name of the array to exec () as the second parameter. I performed this step in Listing 9, with $data as the name of the array.
Listing 9. Capturing the result of an array of data from exec ()
Copy CodeThe code is as follows:
$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 the array, you can do some processing on each row. For example, you can partition the first space, store the detached 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 as exec () and makes the return code available.
list. System () command
Copy CodeThe code is as follows:
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 I 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 will use PassThru (). In general, I use different functions on different occasions, and sometimes they are 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 perfect for using shell commands, but don't know how to use them, I'll give you some insight here.
If you are writing an application that provides a variety of backup or file transfer capabilities, you can choose to run the rsync-supported shell script 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 based on the user's command or cron job.
For example, if a user has the appropriate permissions in your application (such as Administrator privileges), he wants to send 50 PDF files from one server to another server. Then, the user needs to navigate to the correct location in the application, click Transfer, select the PDF to send, and click Submit. In this process, the form should have a PHP script that uses the return option variable to run the Rsync script through PassThru () so that you know if the problem is occurring, as shown below.
Listing 11. Sample PHP script to run the rsync script via PassThru ()
Copy CodeThe 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 those processes or files, you can easily do this with one of the commands summarized in this article. For example, a simple grep command can help you find files that match a specific search condition. Use it with the EXEC () command to save the results to an array, which allows you to build an HTML table or form that further allows you to run other commands.
So far, I've talked about user-generated events--the user just presses a button or clicks a 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 in a PHP script. Why do you do this? It seems to be superfluous, isn't it? That's not true-you need to think about it, you can run a backup script from 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 the 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 an exhaustive (verbose) mode, which is useful for diagnosing problems later).

--------------------------------------------------------------------------------
Safety
Here's a brief discussion of security: If you accept user input and pass information to the shell, it's a good idea to filter user input. Remove 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 a list.
For example, you run a transfer program that accepts a list of files as parameters, and you should list all the 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 running shell scripts and other commands using PHP commands. These PHP commands include shell_exec (), exec (), PassThru (), and System (). You should now practice the knowledge you have learned in your own applications.

http://www.bkjia.com/PHPjc/324262.html www.bkjia.com true http://www.bkjia.com/PHPjc/324262.html techarticle all of these commands derive a subprocess that runs the commands or scripts that you specify, and each child process captures them when the command output is written to standard output (stdout). SHELL_EX ...

  • Related Article

    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.