How to integrate PHP and C program?

2019-08-08 16:27发布

问题:

Let me put my problem in a simple way. I have written a C program, which i will keep in my server. Now i am developing a website using PHP, so that other users can also have access to my stand alone C program.

So here i want my PHP to take input from users and bring that input and run my C program and then again take the results of the C program back to the users using PHP(probably using the same website itself).

Please suggest me how to do it. It would be easier for me to understand if you can tell me using simple program. For example my C program has a function that adds two numbers. The users can provide their input (the numbers) using my website. Then PHP will somehow interact with C function and return the results to the user.

回答1:

Just use the php exec command. I'm assuming you have access to the actual C executable. http://www.php.net/manual/en/function.exec.php

<?php
// outputs the username that owns the running php/httpd process
// (on a system with the "whoami" executable in the path)
echo exec('whoami');
?>


回答2:

Cgi-bin in Apache can execute any kind of executable on your server. PHP is typically run as an Apache module for performance purposes, but can also be run by Cgi-bin.

You could write a Cgi script (Typically in PERL) to execute your C program. You could simply write to a text-file with your C program and then accessed the same file in PHP.



回答3:

You'll have to make a C program which parses command line arguments, like this:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    printf("%d", atoi(argv[1]) + atoi(argv[2]));
    return 0;
}

Then call it from PHP with exec which can put what your C program outputs to stdout into an array. See http://se2.php.net/function.exec.



标签: php c web