views:

86

answers:

1

Hi all,

I'm doing a bit of coursework for university and I'm completely baffled. Basically I've made a basic web server (which uses sockets) in C. I've now got to make it so that any .php file, is run through the php compiler and output.

The problem I'm having is that I've tried using system() and execlp() (the latter was recommended by our lecturer) and cant find out how to get it to show on the page instead of the terminal.

Here's an extract showing the code I've currently got. Please excuse all the comments...as you can see I've been trying all sorts to get it to work!

CODE:

if(strncmp(resource, ".php", 4)==1) {
 //cout << "test";

int php;

  int phppipefds[2], phppid;
  char phpc;
  pipe(phppipefds);
  phppid = fork();
  if(phppid == 0) { // child will read pipe 
 close(0); // close stdin
 dup2(phppipefds[0],0); // read pipe on stdin
 close(phppipefds[1]); // we dont need to write pipe
 execlp("/Applications/MAMP/bin/php5/bin/php", "php", httppath, NULL); 
 cerr << "exec failed\n"; 
 exit(1);
}
// parent, if we redirect stdout printf will send down pipe 
close(1); 
dup2(phppipefds[1],1); // write pipe on stdout
close(phppipefds[1]); // dont need 2 write descriptors
close(phppipefds[0]); // we dont need to read pipe
cout << "words \ngoing \ndown \npipe \nbeing \nsorted\n"; 
close(1); // must close pipe or sort will hang
wait(0);

//php = system("/Applications/MAMP/bin/php5/bin/php /Users/rickymills/webserver/pages/test.php");
//strcat(resp, );
//strcat(resp, php);
 }

The last few lines are where I've been trying all sorts to get this thing to work.

The actual part where everything is dumped to the browser windows is just below the above code:

 write(connsock, resp, rd);
 exit(1);
} 

Does anyone have any idea how I can get this to the browser window? I would have thought the best way would be to get the php output into a variable, and combine it with 'resp' before the connsock write out, is this correct?

Thanks for your time.

+1  A: 

Try using popen() instead of system() or execlp().

The popen() function opens a process by creating a pipe, forking, and invoking the shell. This should allow you to redirect the PHP output back into your program rather than to the terminal.

char buf[BUFSIZ];
FILE *fp;

if ((fp= popen("/bin/php -f /webserver/pages/test.php", "r")) != NULL)
{
    /* Read from the PHP command output */ 
    while (fgets(buf, BUFSIZ, fp) != NULL)
    {
        /* Process the output from PHP as desired */
        ...
    } 

    (void) pclose(ptr);
}

fclose(fp);
jschmier