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


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

通常用c寫一個外部小程序,然后使用上述命令可以在php中調用

1. exec()

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

$command要執行的外部程序

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

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

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

如下示例:

test.c

#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到可執行文件

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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM