php - 在基于 C 的 Web 服务器上执行和输出 PHP - 卡住了!

标签 php c http unix sockets

我正在做一些大学类(class),但我完全感到困惑。基本上,我已经用 C 语言制作了一个基本的 Web 服务器(使用套接字)。我现在必须制作它,以便任何 .php 文件都可以通过 php 编译器运行并输出。

我遇到的问题是我已经尝试使用 system() 和 execlp()(后者是我们的讲师推荐的)并且无法找到如何让它显示在页面而不是终端上。

这是显示我当前获得的代码的摘录。请原谅所有评论...如您所见,我一直在尝试各种方法让它发挥作用!

代码:

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);
 }

最后几行是我一直在尝试各种方法让这个东西工作的地方。

将所有内容转储到浏览器窗口的实际部分就在上面的代码下面:

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

有谁知道我怎样才能把它放到浏览器窗口?我原以为最好的方法是将 php 输出放入一个变量中,并在 connsock 写出之前将其与 'resp' 组合,这样正确吗?

感谢您的宝贵时间。

最佳答案

尝试使用 popen() 而不是 system() 或 execlp()。

popen() 函数通过创建管道、 fork 和​​调用 shell 打开一个进程。这应该允许您将 PHP 输出重定向回您的程序而不是终端。

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);

关于php - 在基于 C 的 Web 服务器上执行和输出 PHP - 卡住了!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2179465/

相关文章:

php - 按 transaction_code 显示数据库组中的数据

php - 在 PHP & MySQL 中使用两个表来显示一个循环结果

php - htaccess 在用户不知情的情况下重定向

c - C程序中的语法错误

c - 如何用 C 语言打印哈希表?

HTTP ETag 复制

php - 如何在 Laravel 中编写这个 SQL 查询?

c - 为什么代码分析不对?

delphi - 使用 Free Pascal 的 TIdHTTPServer 的 UTF-8 响应

http - curl get to angular 2 http get 请求