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, char **argv) { //printf ("Number of parameters:%d\n", argc-1); int a = ATOL (argv[1]); int b = ATOL (argv[2]); int sum = a + b; printf ("%d\n", sum); return 0;}
After saving, perform compilation: gcc test.c-o test compiles a test executable file in the current directory, through the ./test 5 12 can execute file see output
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>
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 ' 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 + +