There are many ways in which PHP calls C + +, most commonly by TCP or HTTP, by sending a request to the cgi/fastcgi written by C + +, and PHP has a way of directly executing an external application, which can affect the security of the system. Easy to be exploited by attackers, so use caution when handling user input
PHP performs external binary commands in several functions, such as exec and PassThru, and the PassThru function can execute commands and return output from external commands, so this is done using PassThru The purpose of the function is to improve computational efficiency when dealing with complex computations, thus improving overall system performance, and here is a simple test case
First write a test.c source file, processing is very simple to two integers to add operations, the code is as follows:
#include <stdio.h>int Main (int argc, argv) { // printf ("Number of arguments:%d\n", argc-1); int a = Atol (Argv[1 ]); int B = Atol (Argv[2 ]); int sum = a + b; printf ( %d\n " return 0 ;}
After saving, compile: gcc test.c-o test will generate a test executable file in the current directory, through ./test 5 Can execute file see output 17
Then write the form and the PHP code, in order to be simple, the current directory is the Web Access root directory, in fact, to put the C + + project in the Web Access directory, in PHP using absolute path call
Form form.html Code:
<!DOCTYPE HTML><HTML><Head> <MetaCharSet= "Utf-8"> <title>PHP Call-C + + case</title></Head><Body> <formMethod= "POST"Action= "add.php"> <Div>Please enter a total of two integers:<inputtype= "text"name= "a" /> + <inputtype= "text"name= "B" /> <inputtype= "Submit"value= "Add" /> </Div> </form></Body></HTML>
PHP Handler add.php Code:
<?PHPHeader("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"The input cannot be empty!" ";}?>
As you can see, in add.php, the call is done by PassThru directly on the command line.
Test results:
A way for PHP to call C + +