1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2002
    Rep Power

    best way to call a PHP script from a C prog?

    I know a way to do this, but can anyone (with more knowledge than me of C and PHP) tell me the best way to do it?

    I would like my php scripts to parse data and display it as it arrives in chunks from a C program. The C program can use multiple threads to produce the raw data much faster than PHP. But the parsing would be quicker to develop and maintain in PHP than C, using regular expressions, etc.

    Example: A form submits to a cgi program written in C. Using multiple threads for speed (which PHP cannot do) the C program simultaneously issues several HTTP requests to different remote servers. As the servers respond, chunks of data become available to be processed (formatted) by a php script and sent to the browser.

    Can/should the C program invoke the PHP scripts, or can/should a PHP script oversee the process?

    Method 1: the C program spawn/call/run/launch the appropriate php script which formats the data and then either outputs the result or returns it to the C program which outputs it. One way to do this is to HTTP POST the data to the PHP script. However, it seems kind of inefficient to do an HTTP post to the same server the program is on! What about using spawn()? Note: it would be best to take advantage of the PHP compiled with Apache. Is there a way to call a PHP script from a C program and have Apache/PHP parse it rather than invoking the PHP CGI?

    Method 2: all of the raw output of the C program returns to the PHP script, the script reads it character by character as it arrives looking for an "end of chunk" marker, parses out a reference to the appropriate php script, and calls that script to format and output the result, continuing until an end of file is reached.

    There has to be a better way to do this.

    Keep in mind: it would be unreasonable to wait for everything to be processed, formatted, etc. before outputting anything to the screen. That would take far too long. Each chunk needs to be processed by a PHP script and displayed as soon as it becomes available.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Rep Power
    You should definitely call your program from PHP. Submit your form to a PHP script and use input to construct command line arguments for starting your C program.

    You can use popen() call for that, it is pretty much the same as popen() in C.

    Is output from your C program serialized so that output from multiple threads doesn't get mixed at random?

    To output in chunks, you just process a chunk, format it and echo it to the client. If you use output buffering in PHP, remember to call ob_flush() after printing each chunk.

IMN logo majestic logo threadwatch logo seochat tools logo