版权声明:原创作品,允许转载,转载时请务必以超链接形式标明文章
原始出处 、作者信息和本声明。否则将追究法律责任。
http://cutebunny.blog.51cto.com/301216/58597
|
用了一下午,终于弄明白了如何在PHP代码中调用外部程序。 在PHP中调用外部程序主要有两个函数,system和exec。 system的原型为string system(string command [, int $return_var])。system本身具有打印命令执行输出的功能,也就是说,程序中的输出printf()PHP页面中显示。如果程序成功执行,则system的返回值为程序输出的最后一行,如果执行失败,返回false。如果调用程序有返回值,则返回值存放在$return_var中。 示例程序如下,以Linux平台为例。 c程序代码: #include "stdio.h" #include "stdlib.h" int main(int argc, char *argv[]) { if(argc!=2){ printf("---------------------/n"); printf("usage: a.out &r/n"); exit(0); } int r,s; r=atoi(argv[1]); s=r*r; printf("ok/n"); printf("haha/n"); return s; } 编译生成a.out文件。 PHP页面代码: <html> <body> <h1>It works!</h1> <?php echo("Congratulations!/n"); $r=3; $s=system("/usr/local/apache/htdocs/php/a.out $r",$ret); echo("s is $s "); echo("ret is $ret "); ?> </body> </html> 执行结果,在页面中显示为: It works!Congratulations! ok haha s is haha ret is 9exec的函数原型为string exec(string command [, array $output [, int $return_var]])。exec本身没有打印程序输出的功能。如果程序执行成功,则exec的返回值为程序输出的最后一行,并且所有的程序输出以数组形式存放在$output中。如果调用程序有返回值,则返回值存放在$return_var中。 示例程序如下,c程序同上。 PHP代码为: <html> <body> <h1>It works!</h1> <?php echo("Congratulations!/n"); $r=3; $s=exec("/usr/local/apache/htdocs/php/a.out $r",$arr,$ret); echo("s is $s "); echo("arr[0] is $arr[0] "); echo("arr[1] is $arr[1] "); echo("ret is $ret "); ?> </body> </html> 执行结果在页面显示为 It works!Congratulations! s is haha arr[0] is ok arr[1] is haha ret is 9本文出自 “bunny的技术之旅” 博客,请务必保留此出处http://cutebunny.blog.51cto.com/301216/58597 本文出自 51CTO.COM技术博客 |
PHP中system,exec调用外部程序,及其参数与返回值 (转)
最新推荐文章于 2021-09-29 10:11:48 发布