您的位置:首页 > 编程语言 > PHP开发

PHP中调用外部程序,及其参数与返…

2013-08-09 17:34 225 查看
在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 9

========================================================================

exec的函数原型为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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: