linux下PHP調用C++的一種方式

由於本人只是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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章