PHP executes the system's external command system () exec () passthru ()

Source: Internet
Author: User

Differences:
System () Outputs and returns the last shell result.
Exec () does not output results. The last shell result is returned. All results can be saved to a returned array.
Passthru () only calls the command and directly outputs the command running result to the standard output device.
Similarities: both of them can obtain the command execution status code.
Demo:

CopyCode The Code is as follows: // System ('dir ');
// Exec ('dir ');
// Passthru ('dir ');
// Echo 'dir ';

As a server-side scripting language, PHP is fully competent for tasks such as simple writing or complex dynamic web pages. But this is not always the case. Sometimes, to implement a function, you must use the external operating system Program (Or a command.
Can an external command be called in a PHP script? If so, how can we do it? What are your concerns? I believe you will be able to answer these questions after reading this article.
Yes?
The answer is yes. Like other programming languages, PHP can call external commands in a program, and it is very simple: just use one or more functions.
Prerequisites
Since PHP is basically used for web program development, security has become an important aspect of consideration. As a result, PHP designers added a security mode to PhP. If running in safe mode, the PHP script will be subject to the following four restrictions:
Execute External commands
Restrictions on opening a file
Connect to the MySQL database
HTTP-based authentication
In security mode, only external programs in a specific directory can be executed, and calls to other programs will be rejected. This directory can be specified by using the safe_mode_exec_dir command in the PHP. ini file, or by adding the -- with-Exec-Dir option to compile PHP. The default value is/usr/local/PHP/bin.
If you call an external command that should be able to output the result (meaning that the PHP script is correct), the result is blank, it is very likely that your network administrator has run php In security mode.
How to do it?
You can use the following three methods to call external commands in PHP:
1) use special functions provided by PHP
PHP provides three specialized functions for executing external commands: System (), exec (), and passthru ().
System ()
Prototype: String System (string command [, int return_var])
The system () function is similar to the one in other languages. It executes the given command, outputs and returns the result. The second parameter is optional and is used to obtain the status code after the command is executed.
Example: Copy code The Code is as follows: <? PHP
System ("/usr/local/bin/Webalizer ");
?>

Exec ()
Prototype: String exec (string command [, String Array [, int return_var])
The Exec () function is similar to system (). It also executes the given command, but does not output the result, but returns the last line of the result. Although it only returns the last line of the command result, the complete result can be obtained using the second parameter array by appending the result row by row to the end of the array. Therefore, if the array is not empty, we recommend that you use unset () to clear it before calling it. Only when the second parameter is specified can the third parameter be used to obtain the command execution status code.
Example:Copy codeThe Code is as follows: <? PHP
Exec ("/bin/LS-L ");
Exec ("/bin/LS-L", $ res );
Exec ("/bin/LS-L", $ res, $ RC );
?>

Passthru ()
Prototype: void passthru (string command [, int return_var])
Passthru () only calls the command and does not return any results, but directly outputs the running result of the command to the standard output device as is. Therefore, the passthru () function is often used to call programs such as pbmplus (a UNIX-based image processing tool that outputs binary original image streams. It can also get the status code of command execution.
Example:Copy codeThe Code is as follows: <? PHP
Header ("Content-Type: image/GIF ");
Passthru ("./ppmtogif Hunte. ppm ");
?>

2) use the popen () function to open the process
The preceding method can only execute commands, but cannot interact with commands. However, sometimes you must enter something into the command. For example, when adding a Linux system user, you must call Su to change the current user to the root user, the su command must enter the root password on the command line. In this case, it is obviously not feasible to use the method mentioned above.
The popen () function opens a process pipeline to execute the given command and returns a file handle. Since a file handle is returned, you can read and write it. In php3, you can only perform a single operation mode on the handle, either write or read. From PhP4, you can read and write the handle at the same time. Unless this handle is opened in a mode (read or write), you must call the pclose () function to close it.
Example 1:Copy codeThe Code is as follows: <? PHP
$ Fp = popen ("/bin/LS-L", "R ");
?>

Example 2:Copy codeThe Code is as follows: <? PHP
/* Add a system user in PHP
The following is a routine. Add a user named James,
The root password is verygood. For reference only
*/
$ Sucommand = "su -- login root -- command ";
$ Useradd = "useradd ";
$ Rootpasswd = "verygood ";
$ User = "James ";
$ User_add = sprintf ("% s" % S % s "", $ sucommand, $ useradd, $ user );
$ Fp = @ popen ($ user_add, "W ");
@ Fputs ($ FP, $ rootpasswd );
@ Pclose ($ FP );
?>

3) use the reverse marker (', that is, the one under the ESC key on the keyboard, and ~ )
This method was not included in the document of PHP before and existed as a secret. The method is very simple. We use two anti-apostrophes to enclose the command to be executed as an expression. The value of this expression is the result of command execution. For example:Copy codeThe Code is as follows: <? PHP
$ Res = '/bin/LS-l ';
Echo'
'. $ Res .'
';
?>

the output of this script is like:
hunte.gif
Hunte. PPM
jpg.htm
jpg.jpg
Passthru. php
what should I consider?
two considerations: security and timeout.
Security first. For example, if you have a small online store, you can store the list of products that can be sold in a file. You have compiled an HTML file with a form, allowing your users to enter their email address, and then send the product list to them. Suppose you have not used the mail () function of PHP (or have never heard of it), you can call the mail program of Linux/Unix system to send this file. The program is like this: copy Code the code is as follows: system ("mail $ to echo "our product directory has been sent to your mailbox: $ to";
?>

with this code, general users are not at risk, but there are actually very large security vulnerabilities. If a malicious user inputs an email address:
'-- bla; mail someone@domain.com then the Command eventually becomes:
'mail -- bla; mail someone@domain.com I believe that no matter which network manager sees such a command, it will scare a cold sweat.
fortunately, PHP provides us with two functions: escapeshellcmd () and escapeshellarg (). The function escapeshellcmd escapes all the characters in a string that may bypass shell and execute another command. These characters have special meanings in shell, such as semicolon (), redirection (>), and reading from a file (<. The escapeshellarg function is used to process command parameters. It adds single quotes on both sides of a given string and escapes the single quotes in the string, so that the string can be safely used as a command parameter.
let's take a look at the timeout issue. If the command to be executed takes a long time, put the command in the background of the system to run it. However, by default, functions such as system () will not be returned until the command is run completely (in fact, they will wait for the output result of the command), which will definitely cause the PHP script to time out. The solution is to redirect the command output to another file or stream, for example, copy Code the code is as follows: system ("/usr/local/bin/order_proc>/tmp/null &");
?>

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.