PHP执行Linux命令的6个常用函数详解
通常情况下,PHP脚本较少直接调用Linux系统命令,但在特定场景下这些功能不可或缺。除了常见的exec和shell_exec外,实际上还有多个相关函数可用。本文将结合手册内容,详细解析这6个用于执行Linux命令的函数。
第一个函数是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。
<?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。
<?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。
<?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命令的函数主要就这几个,可能还有其他未提及的方法,欢迎读者补充。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。