I would like to execute a PHP script from a C program and store the returning content in to a C variable.
I tried like following but it doesn't work:
C:
printf("calling php function\n");
execl("/usr/bin/php -q", "/var/www/html/phpinfo.php", NULL);
printf("End php function\n");
PHP:
<?php
echo "hello";
?>
Environment:
- PHP 5.2.6
- Apache 2.0
- Fedora Core 10
Also suggest any other better way to do this.
Short answer here is to use
system()
orpopen()
rather thanexecl()
. Seeing as Jason has already posted a good answer about usingpopen()
, I'll skip that and explain how to useexecl()
just in case you actually care. Most likely, this is all unnecessary technical mumbo jumbo--but dammit, I had most of this typed out already as a long prelude before discussingpopen()
and I'm not throwing it away now!Firstly...
When calling
execl()
all of the command-line arguments need to be passed separately. Also, the first argument must be repeated asargv[0]
in any program'smain()
is traditionally the name of the program. So the fixed call should look like:(I added the cast to
(char *)
to ensure that a null pointer is passed as the final argument rather than the integer 0, ifNULL
happens to be defined as0
and not(void *) 0
, which is legal.)However...
This gets the
execl()
call right, but there's a bigger problem. Theexec
family of functions are almost always used in combination withfork()
and some complicatedpipe()
juggling. This is because theexec
functions do not run the program in a separate process; they actually replace the current process! So once you callexecl()
, your code is done. Finished.execl()
never returns. If you just call it like you've done you'll never get to see what happens as your program will magically transform into a/usr/bin/php
process.OK, so what's this about
fork()
andpipe()
? At a high level, what you've got to do is split your process into two processes. The parent process will continue to be "your" process, while the child process will immediately callexecl()
and transform itself into/usr/bin/php
. Then if you've wired the parent and child processes together correctly they'll be able to communicate with each other.To make a long story short, if you're still here and haven't nodded off you should consult the wise oracle Google for way more details about all of this. There are plenty of web sites out there giving even more (!) in-depth details about how to do the
fork
/exec
dance.I won't leave you hanging though. Here's a function I use for my own programs that does exactly what I've outlined. It is very similar to
popen()
in fact, the only difference being that the caller can access the child'sstderr
stream in addition tostdin
andstdout
.Code...