How to call c method in php: first write a [test.c] source file; then save it and execute compilation; then php handler [add.php] code; finally in [add.php] Just execute the command in the command line directly through passthru to complete the call.
How php calls c method:
There are many ways for php to call c/c, the most commonly used one is Called through tcp or http, it is implemented by sending a request to call cgi/fastcgi written in c/c. In addition, php has a way to directly execute external applications. This method will affect system security and can easily be exploited by attackers. , so user input must be handled carefully when using it
PHP has several functions for executing external binary commands, such as exec and passthru, and the passthru function can execute commands and return the output of external commands, so this time Just use passthru to achieve it. The purpose of PHP calling c/c function is to improve the calculation efficiency when processing complex calculations, thereby improving the overall system performance. The following is a simple test case
First write atest .c
source file, the processing is very simple, just add two integers, the code is as follows:
#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; }
After saving, execute compilation: gcc test.c -o test
After compilation The test executable file will be generated in the current directory. You can execute the file through ./test 5 12
to see the output 17
and then write the form and php code. For simplicity, the current directory is web To access the root directory, actually put the C/C project outside the web access directory, and use the absolute path in php to call the
form.html code:
<!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 handleradd.php
Code:
<?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 "输入不能为空!"; } ?>
It can be seen that in add.php, the call is completed by directly executing the command in the command line through passthru
Test results:
##Related learning recommendations:
The above is the detailed content of How to call c method in php. For more information, please follow other related articles on the PHP Chinese website!