由于本人只是PHP小白,C++方面完全不懂,通过网上查阅资料后,整合出一个确实能用的一篇文章,方便以后自己查找。
php执行外部二进制命令的函数有好几个,比如exec和passthru,并且passthru函数能执行命令并且可以返回外部命令的输出,所以本次就使用passthru来实现,php调用c/c++函数的目的就是处理复杂计算时提高计算效率,从而提高整体的系统性能,下面是一个简单的测试案例
首先在linux下编写一个test.c源文件,处理很简单就是对两个整数进行加法运算,代码如下:
#include<stdio.h>
int main(int argc, char **argv) {
//printf("参数个数:%d\n", argc-1);
int a = atol(argv[1]);
int b = atol(argv[2]);
int sum = a + b;
printf("%d\n", sum);
return 0;
}
保存后,在linux下执行编译: gcc test.c -o test
编译后会在当前目录下生成test可执行文件,通过 ./test 5 12
可以执行文件看到输出17
然后写表单和php代码,为了简单,当前目录就是web访问根目录,实际中要把C/C++项目放在web访问目录之外,在php中使用绝对路径调用
表单form.html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php调用c/c++案例</title>
</head>
<body>
<form method="post" action="add.php">
<div>
请输入两个整数:
<input type="text" name="a" />
+
<input type="text" name="b" />
<input type="submit" value="相加" />
</div>
</form>
</body>
</html>
php处理程序add.php代码:
<?php
header("Content-Type:text/html; charset=utf-8");
if(isset($_POST['a']) && isset($_POST['b']) && !empty($_POST['a']) && !empty($_POST['b'])) {
$command = './test '.$_POST['a'].' '.$_POST['b'];
$result = passthru($command);
print_r($result);
} else {
echo "输入不能为空!";
}
?>
注意!使用passthru()函数需要打开配置php.ini!
先检查下php配置文件php.ini中是有禁止这是个函数。
cd进入到php.ini所在目录
查找“disable_functions”所在行:
grep -n "disable_functions" php.ini
查询到行数后:
vi php.ini
找到 disable_functions所在行,配置如下:
disable_functions = 各种函数名;
如果“disable_functions=”后面有接passthru函数,将其删除。
默认php.ini配置文件中是不禁止你调用执行外部命令的函数的。
测试结果:
大功告成!!!
相关文章:
php调用c/c++的一种方式:http://www.cnblogs.com/freeweb/p/5645699.html
PHP执行系统外部命令函数:exec()、passthru()、system()、shell_exec():http://blog.csdn.net/beyond__devil/article/details/53868309
linux下查找某个字符串所在行:http://blog.csdn.net/baozoumingren/article/details/75304350