简体   繁体   中英

Execute and output PHP on a C based web-server - Stuck!

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.

Try using instead of system() or execlp(). 而不是system()或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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM