一.php执行系统命令的4个方法
1.system()
同 C 版本的 system() 函数一样-执行shell命令也就是向dos发送一条指令, 本函数执行 command 参数所指定的命令, 并且输出执行结果。
如果 PHP 运行在服务器模块中, system() 函数还会尝试在每行输出完毕之后, 自动刷新 web 服务器的输出缓存
官方示例:
<?php
echo '<pre>';
// 输出 shell 命令 "ls" 的返回结果
// 并且将输出的最后一样内容返回到 $last_line。
// 将命令的返回值保存到 $retval。
$last_line = system('ls', $retval);
// 打印更多信息
echo '
</pre>
<hr />Last line of the output: ' . $last_line . '
<hr />Return value: ' . $retval;
?>
2.exec
执行一个外部程序
exec ( string $command [, array &$output [, int &$return_var ]] ) : string
command 要执行的命令。
output 如果提供了 output 参数, 那么会用命令执行的输出填充此数组, 每行输出填充数组中的一个元素。
数组中的数据不包含行尾的空白字符,例如 \n 字符。 请注意,如果数组中已经包含了部分元素,exec()
函数会在数组末尾追加内容。如果你不想在数组末尾进行追加, 请在传入 exec() 函数之前 对数组使用 unset() 函数进行重置。return_var 如果同时提供 output 和 return_var 参数, 命令执行后的返回状态会被写入到此变量。
返回值 ¶ 命令执行结果的最后一行内容
<?php
echo exec("ls -a");
?>
3.shell_exec
shell_exec ( string $cmd ) : string
shell_exec — 通过 shell 环境执行命令,并且将完整的输出以字符串的方式返回
cmd
要执行的命令。
<?php
$output = shell_exec('ls -lart');
echo "<pre>$output</pre>";
?>
4.passthru
执行外部程序并且显示原始输出
passthru ( string $command [, int &$return_var ] ) : void
同 exec() 函数类似, passthru() 函数 也是用来执行外部命令(command)的。 当所执行的 Unix
命令输出二进制数据, 并且需要直接传送到浏览器的时候, 需要用此函数来替代 exec() 或 system() 函数。 常用来执行诸如
pbmplus 之类的可以直接输出图像流的命令。 通过设置 Content-type 为 image/gif, 然后调用 pbmplus
程序输出 gif 文件, 就可以从 PHP 脚本中直接输出图像到浏览器。
command
要执行的命令。
return_var
如果提供 return_var 参数, Unix 命令的返回状态会被记录到此参数。
当用户提供的数据传入此函数,使用 escapeshellarg() 或 escapeshellcmd() 来确保用户欺骗系统从而执行任意命令。