php 执行外部命令exec() system() passthru()
php 执行部命令exec() system() passthru()
通常用c写一个外部小程序,然后使用上述命令可以在php中调用
1. exec()
string exec ( string
$command
[, array &$output
[, int &$return_var
]] )$command要执行的外部程序
$output 会把程序中所有的输出结果输出到该数组中;如c中的printf(); 可以利用这个往外部返多个值;
$return_var 该程序执行结果的返回值;比对 C程序中 的return 0;
string 返回值即程序输出的最后一个行,即最后一个printf()
如下示例:
test.c
#include <stdio.h> int main(int argc, const char * argv[]) { if (argc==2) { printf("this is parm %s\n",argv[1]); } printf("Hello, World!\n"); return 0; }
编译test.c到可执行文件
cocoaPro:Desktop cocoajin$ gcc -o test main.c cocoaPro:Desktop cocoajin$ ./test ppp this is parm ppp Hello, World! cocoaPro:Desktop cocoajin$ ls |grep test test cocoaPro:Desktop cocoajin$
test.php
<?php echo "hello world from php <br>"; exec("./test 'aaa'", $outArry,$dret); echo $dret.'<br>'; echo var_dump($outArry); ?>
访问test.php输出
hello world from php 0 array(2) { [0]=> string(16) "this is parm aaa" [1]=> string(13) "Hello, World!" }
注意上面的test 程序,如果php的环境是linux的,就要用linux下的gcc编译,winddows环境,就要用win下的gcc编译;
在linux下编译的test程序,在win下是不能用的
2.system()
string system ( string $command
[, int &$return_var
] )
$command 要执行的命令
$return_var 程序的返回值;即C程序中的return值0;
string 函数返回值是,程序执行的最后一行输出;
3. passthru()
void passthru ( string $command
[, int &$return_var
] )
$command 要执行的命令
$return_var 程序的返回值;即C程序中的return值0;
无返回值;
总结:
这几个命令功能真强大,php结合C,可以做很多事情了!
参考:http://php.net/manual/zh/function.exec.php
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具