A way for PHP to call C + +

Source: Internet
Author: User

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 + +

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.