php+方法返回多个参数,PHP中调用外部程序,及其参数与返回值
用了一下午,終于弄明白了如何在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頁面代碼:
It works!
echo("Congratulations!\n");
$r=3;
$s=system("/usr/local/apache/htdocs/php/a.out $r",$ret);
echo("s is $s? ");
echo("ret is $ret? ");
?>
執行結果,在頁面中顯示為:
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代碼為:
It works!
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? ");
?>
執行結果在頁面顯示為
It works!Congratulations! s is haha arr[0] is ok arr[1] is haha ret is 9
總結
以上是生活随笔為你收集整理的php+方法返回多个参数,PHP中调用外部程序,及其参数与返回值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php手工注入语句,PHP+MySQL
- 下一篇: 动态规划算法php,php算法学习之动态