Home  >  Article  >  Backend Development  >  PHP command line tools shell_exec, exec, passthru, system detailed usage introduction_PHP tutorial

PHP command line tools shell_exec, exec, passthru, system detailed usage introduction_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:24:39961browse

All of these commands spawn a child process that runs the command or script you specify, and each child process captures the command output as it is written to standard output (stdout).

shell_exec()

The shell_exec() command line is really just a variation of the backtick (`) operator. If you've ever written a shell or Perl script, you know that you can capture the output of other commands inside the backtick operator. For example, Listing 1 shows how to use backticks to get the word count for each text (.txt) in the current directory.

Listing 1. Counting the number of words using backticks

Copy the code The code is 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 desired result. It is assumed here that there are some text files in the same directory.

Listing 2. Running the same command in shell_exec()
Copy the code The code is as follows:

$results = shell_exec('wc -w *.txt');
echo $results;
?>

You can see it 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 returns the result as a string.
Figure 1. Results of running a shell command via shell_exec()
PHP 命令行工具 shell exec, exec, passthru, system a669388d201eb3de
Note that just using the trailing apostrophe operator will give you the same result, as shown below.
Listing 3. Using only the trailing apostrophe operator
Copy the code The code is as follows:

$results = `wc -w *.txt`;
echo $results;
?>

Listing 4 gives a simpler method.
Listing 4. A simpler method
Copy the code The code is as follows:

echo `wc -w *.txt`;
?>

It is important to know that a lot can be done through the UNIX command line and shell scripts. For example, you can use pipes to connect commands. You can even create a shell script within it using operators and just call the shell script (with or without parameters as needed).

For example, if you only want to count the words of the first 5 text files in that directory, you can use a vertical bar (|) to connect the wc and head commands. Alternatively, you can place the output inside a pre tag to render it more beautifully in a web browser, as shown below.

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

$results = shell_exec('wc -w *.txt | head -5');
echo "".$results . "";
?>

Figure 2 demonstrates the results of running the script in Listing 5.
Figure 2. Results from shell_exec() running a more complex shell command
PHP 命令行工具 shell exec, exec, passthru, system f3a26409a75568a6
Later in this article, you will learn how to pass arguments to these scripts using PHP. Now you can think of this as a way to run a shell command, but remember that you can only see standard output. If an error occurs with a command or script, you won't see the standard error (stderr) unless you add it to stdout via a pipe.

passthru()

passthru() allows you to run external programs and display the results on the screen. You don't need to use echo or return to see the results; they will be displayed on the browser. You can add optional parameters, which are variables that hold the code returned from the 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 counting script I ran in the previous section. As you can see, I also added a $returnval variable that contains the return code.

Listing 6. Use the passthru() command to run the word counting script
Copy the code The 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. The result of running the passthru() command using the return code
PHP 命令行工具 shell exec, exec, passthru, system 3cec849f89db6011
In Listing 7, I introduced a small error by removing the dash (-) in front of the 5 in the header of the script .
Listing 7. Introducing a bug in the word count script
Copy the code 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 does not run as expected. What you get is a blank screen, a horizontal line, and a return value of 1, as shown in Figure 4. This return code usually indicates that some error occurred. Finding and fixing bugs is much easier if you can test the return code.
Figure 4. View error code when using passthru()
PHP 命令行工具 shell exec, exec, passthru, system 9e8f40d55fd5196f
exec()
The exec() command is similar to shell_exec(), except that it Returns the last line of output and optionally populates the array with the command's complete output and error code. Listing 8 shows what happens when you run exec() without capturing the data in the data array.
Listing 8. Running exec() without capturing data in the data array
Copy the code The 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 capture the results in an array, add the name of the array as the second argument to exec(). I performed this step in Listing 9, using $data as the name of the array.
Listing 9. Capturing the results of the data array from exec()
Copy the code The 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. For example, you can divide at the first space, store separated values ​​in a database table, or apply specific formatting or tags to each row.
system()
As shown in Listing 10, the system() command is a hybrid. It directly outputs whatever it receives from the external program, just like passthru(). It also returns the last line like exec() and makes the return code available.
Listing 10. system() command
Copy code The 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? It all depends on your needs.
Mostly I use exec() commands and data arrays for everything. Or use shell_exec() for simpler commands, especially if you don't care about the results. If I just need to return a shell script, I use passthru(). Often I use different functions on different occasions, and sometimes they are interchangeable. It all depends on my mood and what I'm trying to achieve.
Another question you might ask is “What are their strengths?”. If you have no clue, or have a project that would be great for using shell commands but don't know how to use them, I'm here to provide some insight.
If you are writing an application that provides various backup or file transfer functionality, you may choose to run an rsync-supported shell script using shell_exec() or one of the other commands provided here. You can write a shell script to include the necessary rsync commands and then use passthru() to execute it based on a user's command or a cron job.
For example, a user with appropriate permissions in your application (such as admin rights) wants to send 50 PDF files from one server to another. The user then needs to navigate to the correct location in the application, click Transfer, select the PDF that needs to be sent, and click Submit. Along the way, the form should have a PHP script that runs the rsync script via passthru() using the return options variable as shown below.
Listing 11. Sample PHP script to run rsync script through passthru()
Copy code The code is 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 easily accomplish this using one of the commands summarized in this article. For example, a simple grep command can help you find files that match specific search criteria. Using it with the exec() command saves the results into an array, which allows you to build an HTML table or form, which in turn allows you to run other commands.
So far, I've discussed user-generated events - whenever the user presses a button or clicks a link, PHP runs the corresponding script. You can also use standalone PHP scripts with cron or other schedulers to achieve some interesting effects. For example, if you have a backup script, you can run it via cron, or package it into a PHP script and run it. Why do this? This seems redundant, doesn't it? That's not the case - you need to think of it this way, you can run the backup script via 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 email. If the script succeeds, you can dump the raw output to a database (for example, rsync has a verbose mode, which is useful for diagnosing problems later).

-------------------------------------------------- ------------------------------------
Security
Let’s briefly discuss security here Sex: If you accept user input and pass the information to the shell, it's better to filter the user input. Remove commands you consider harmful and disallowed, such as sudo (run as superuser) or rm (remove). In fact, you probably don't want the user to send an open request, but instead let them choose from a list.
For example, if you run a transfer program that accepts a list of files as an argument, you should list all the files via a series of checkboxes. 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 Basics of running shell scripts and other commands using PHP commands. These PHP commands include shell_exec(), exec(), passthru(), and system(). Now, you should put what you learned into practice in your own application.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324262.htmlTechArticleAll these commands spawn a child process for running the command or script you specify, and each child process will Captures command output as it is written to standard output (stdout). shell_ex...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn