本文作者:心月

在PHP项目中利用system函数执行shell命令

心月IT博客 10-27
在PHP项目中利用system函数执行shell命令摘要:在php项目开发中,如果能够在项目内执行shell命令,将可以实现更多的功能;此外,如果可以用具有同php相同功能的shell命令来替代,也可以提升项目的性能和效率。而php的system函数就可以实现在php中执行shell命令。

        在php项目开发中,如果能够在项目内执行shell命令,将可以实现更多的功能;此外,如果可以用具有同php相同功能的shell命令来替代,也可以提升项目的性能和效率。而php的system函数就可以实现在php中执行shell命令。


1、system执行shell命令

$shell = "ls -la /home/ubuntugx/桌面";
	echo "<br>";
	echo "<br>";
	echo "<br>";
    echo "<pre>";
    echo "shell命令<font color='red'>$shell</font>执行结果:<br>";
    system($shell, $status);
    echo "</pre>";


2、执行shell脚本文件

        命令中的test.sh是一个监控ngingx进程是否运行的shell脚本文件

$shell = "sh /home/ubuntugx/桌面/test.sh";
	echo "<pre>";
	echo "shell命令<font color='red'>$shell</font>执行结果:<br>";
    system($shell, $status);
    echo "</pre>";


3、给shell脚本文件传递参数并执行

        在 fun.sh 文件中定义了一个可以进行简单四则运算的函数,需要传递参数:数值1 、运算符 、 数值2,然后根据传递的参数进行相应的计算

$shell = "sh /home/ubuntugx/桌面/fun.sh 20 + 30";
	echo "<pre>";
	echo "shell命令<font color='red'>$shell</font>执行结果:<br>";
    system($shell, $status);
    echo "</pre>";


4、执行自定义函数库中的函数

test2.sh 中引入了自定义函数库文件,并使用了自定义函数 add :实现两个数相加

$shell = "sh /home/ubuntugx/桌面/test2.sh";
	echo "<pre>";
    system($shell, $status);
    echo "shell命令<font color='red'>$shell</font>执行结果:<br>";
    echo "</pre>";

以上4中运用的执行结果:

    

php中执行shell命令的结果展示

        通过截图可以发现,在使用system执行shell命令的结果和linux系统中执行shell命令的结果完全一致。

以上实例都是在linux系统中的PHP环境下执行的,在windows系统中使用system函数执行shell命令时似乎有点问题


文章版权及转载声明:

本文由 心月IT技术博客 博主整理于 10-27
若转载请注明原文及出处:https://www.xinyueseo.com/other/441.html

分享到:
赞(
发表评论
快捷输入:

验证码

    评论列表 (有 0 条评论,人围观)参与讨论