Home > Article > Backend Development > How to handle when php cannot call external commands
passthru() Prototype: void passthru (string command [, int return_var]) passthru() only calls the command and does not return any results, but outputs the running results of the command directly to the standard output device as is. Therefore, the passthru() function is often used to call programs like pbmplus (a tool for processing images under Unix that outputs a binary stream of original images). It can also get the status code of command execution. Example:
2, use the popen() function to open the process The above method can only simply execute the command, but cannot interact with the command. But sometimes you must enter something into the command. For example, when adding a Linux system user, you need to call su to change the current user to root, and the su command must enter the root password on the command line. In this case, it is obviously not possible to use the method mentioned above. Thepopen() function opens a process pipe to execute the given command and returns a file handle. Since a file handle is returned, you can read and write to it. In PHP3, this kind of handle can only be used in a single operation mode, either writing or reading; starting from PHP4, it can read and write at the same time. Unless the handle is opened in one mode (read or write), the pclose() function must be called to close it. Example 1:
Example 2:
3, use the backtick (`, which is under the ESC key on the keyboard That, and ~ are on the same top) The method is very simple. Use two backticks to enclose the command to be executed as an expression. The value of this expression is the result of the command execution. like:
The output is similar to this: hunte.gif hunte.ppm jpg.htm jpg.jpg passthru.php There are two issues to consider: security and timeouts. Let’s look at safety first. For example, you have a small online store, so the list of products available for sale is placed in a file. You write an HTML file with a form that asks your users to enter their email address and then sends them a list of products. Assuming that you have not used PHP's mail() function (or have never heard of it), you call the mail program of the Linux/Unix system to send this file. The program looks like this:
Using this code will not cause any danger to ordinary users, but in fact there is a very large security vulnerability. If a malicious user enters such an EMAIL address: '--bla mail someone@domain.com ) and read from file ( Timeout issue If the command to be executed takes a long time, the command should be run in the background of the system. But by default, functions such as system() wait until the command is finished running before returning (actually, they have to wait for the output of the command), which will definitely cause the PHP script to time out. Solution: Redirect the output of the command to another file or stream, example:
|