tags:

views:

211

answers:

4

I am trying to write an application that will use PHP as a scripting language. The application is a CGI handler, and I want to be able to call PHP pages from it.

I am looking for code that will let me initialize PHP inside the C program and then pass it either a buffer containing the php code, or a filename, for it to parse. I want to take the output from that and be able to run it through a function in the CGI program.

A: 

Maybe this will work for what you need?:

FILE *f = fopen ("script.php", "wt");
fprintf (f, "<?php\n"
   "// script here\n"
   "?>\n");
fclose (f);
system ("php -f script.php >script.out");

f = fopen ("script.out", "r");
char buf [1000];
fgets (f, buf, sizeof buf);
// etc.

Edit: Well since you can't use system(), there appears to be no recommended way to link the PHP interpreter into a C program. The recommended solutions are similar to using system with forks and pipes. Either that, or place the PHP script on a webserver and connect to it from the C program.

wallyk
Sorry I have to say I don't like your approach, it requires too much IO operations and it is not flexible at not (e.g: you need to readjust your buffer according to file size), also it needs be triggered by the web server to render the output script which adds another layer of complexity.
Jay Zeng
+1  A: 

Try the PHPEmbed library. It's for C++, rather than C, but it might still work for you, depending on the project requirements.

outis
Good link. It wont work for me, but I can use it to see how to code what I need. Thank you.
The Big Spark
+2  A: 

The book Extending and Embedding PHP by Sara Golemon (amazon) has a chapter about embedding PHP in a C programm, which might interest you.

If you want a preview, from what I remember, some pages are avaible on Google books, for instance.


Here's a quick quote (from the beginning of chapter 20.) :

In addition to loading external scripts, as you saw in the last chapter, your PHP embedding application can also execute smaller snippets of arbitrary code using the underlying function that implements the familiar userspace eval() command.

Pascal MARTIN
This book will be added to my library the first chance I get.
The Big Spark
I have not put into practice what's written in it, but it's an interesting read anyway :-)
Pascal MARTIN
A: 

I would check out how they've implemented the php command line binary. It seems the main function is in php_cli.c

And it calls php_execute_scrip and a bunch of other functions which looks promising.

Martin Wickman