php 執行外部命令exec() system() passthru()

php 執行部命令exec() system() passthru()php

一般用c寫一個外部小程序,而後使用上述命令能夠在php中調用linux

1. exec()小程序

string exec ( string $command [, array &$output [, int &$return_var ]] )

$command要執行的外部程序數組

$output 會把程序中全部的輸出結果輸出到該數組中;如c中的printf(); 能夠利用這個往外部返多個值;函數

$return_var 該程序執行結果的返回值;比對 C程序中 的return 0; this

string 返回值即程序輸出的最後一個行,即最後一個printf()spa

以下示例:.net

test.ccode

#include <stdio.h>

int main(int argc, const char * argv[]) {
    if (argc==2) {
        printf("this is parm %s\n",argv[1]);
    }
    printf("Hello, World!\n");
    return 0;
}

 

編譯test.c到可執行文件blog

cocoaPro:Desktop cocoajin$ gcc -o test main.c 
cocoaPro:Desktop cocoajin$ ./test ppp
this is parm ppp
Hello, World!
cocoaPro:Desktop cocoajin$ ls |grep test
test
cocoaPro:Desktop cocoajin$ 

test.php

<?php 
        
        echo "hello world from php <br>";
exec("./test 'aaa'", $outArry,$dret);

        echo $dret.'<br>';

        echo var_dump($outArry);
    
 ?>

訪問test.php輸出

hello world from php 
0
array(2) { [0]=> string(16) "this is parm aaa" [1]=> string(13) "Hello, World!" }

 

注意上面的test 程序,若是php的環境是linux的,就要用linux下的gcc編譯,winddows環境,就要用win下的gcc編譯;

  在linux下編譯的test程序,在win下是不能用的

 

2.system()

string system ( string $command [, int &$return_var ] )

$command 要執行的命令

$return_var 程序的返回值;即C程序中的return值0;

string 函數返回值是,程序執行的最後一行輸出;

 

3. passthru()

void passthru ( string $command [, int &$return_var ] )

$command 要執行的命令

$return_var 程序的返回值;即C程序中的return值0;

無返回值;

 

總結:

這幾個命令功能真強大,php結合C,能夠作不少事情了!

參考:http://php.net/manual/zh/function.exec.php

相關文章
相關標籤/搜索