PHP执行Linux命令函数概览
通常情况下,PHP较少用于执行Linux命令,但在特定场景下可能需要此类功能。此前仅知晓exec与shell_exec两个函数,实际上结合手册资料,共有六种函数可用于执行Linux命令,下文将逐一介绍。
exec函数及其返回结果分析
第一种是exec函数。
<?php
$test = "ls /tmp/test"; //ls是linux下的查目录,文件的命令
exec($test,$array); //执行命令
print_r($array);
?>
其返回结果示例如下:
[root@krlcgcms01 shell]# php ./exec.php
Array
(
[0] => 1001.log
[1] => 10.log
[2] => 10.tar.gz
[3] => aaa.tar.gz
[4] => mytest
[5] => test1101
[6] => test1102
[7] => weblog_2010_09
)
system函数输出特性说明
第二种是system函数。
<?php
$test = "ls /tmp/test";
$last = system($test);
print "last: $last\n";
?>
该函数的返回结果展示为:
[root@krlcgcms01 shell]# php system.php
1001.log
10.log
10.tar.gz
aaa.tar.gz
mytest
test1101
test1102
weblog_2010_09
last:weblog_2010_09
passthru与popen函数简介
第三种为passthru函数。
<?php
$test = "ls /tmp/test";
passthru($test);
?>
第四种涉及popen函数。
<?php
$test = "ls /tmp/test";
$fp = popen($test,"r"); //popen打一个进程通道
while (!feof($fp)) { //从通道里面取得东西
$out = fgets($fp, 4096);
echo $out; //打印出来
}
pclose($fp);
?>
proc_open与shell_exec函数介绍
第五种方法使用proc_open函数。
<?php
$test = "ls /tmp/test";
$array = array(
array("pipe","r"), //标准输入
array("pipe","w"), //标准输出内容
array("pipe","w") //标准输出错误
);
$fp = proc_open($test,$array,$pipes); //打开一个进程通道
echo stream_get_contents($pipes[1]); //为什么是$pipes[1],因为1是输出内容
proc_close($fp);
?>
第六种方式是shell_exec函数。
<?php
$test = "ls /tmp/test";
$out = shell_exec($test);
echo $out;
?>
多函数返回结果对比总结
popen、passthru、proc_open以及shell_exec这四个函数的返回结果情况如下:
[root@krlcgcms01 shell]# php test.php
1001.log
10.log
10.tar.gz
aaa.tar.gz
mytest
test1101
test1102
weblog_2010_09
目前所能发现的能够执行Linux命令的PHP函数即以上这些,或许还存在其他方法,欢迎读者补充完善。