如何从C运行一些PHP代码

时间:2012-10-05 10:27:11

标签: php c linux

我有一些代码可以正常工作。

  FILE *pipe_fp;
  if((pipe_fp = popen("php", "w")) == NULL) {
    perror("popen(PHP)");
    exit(1);
  }

  fputs("<?php echo process('xx'); ?>", pipe_fp);
  int ret = pclose(pipe_fp);
  if(WIFEXITED(ret))
    printf("%d\n", WEXITSTATUS(ret));

问题在于我尝试这样的事情:

// up to this point i am starting a socket servers and wait for clients
int bSize;
int nSize;
char buffer[MAXBUF+1];
char receive[MAXBUF+1];
while(1) {
  bSize = recv(new_fd, buffer, MAXBUF, 0);
  if(bSize > 0) {
    buffer[bSize] = '\0';
    strcat(receive, buffer);
  }
}

// I rote this part based on this post: http://stackoverflow.com/questions/1383649/concatenating-strings-in-c-which-method-is-more-efficient
char * first= "<?php echo process('";
char * second = "'); ?>";
char * code = NULL;
asprintf(&code, "%s%s%s", first, receive, second);

// the above code somes here, i just copied the part that has changed
fputs(code, pipe_fp);

我尝试过其他所有导致失败的例子。 我今天3天在C。

3 个答案:

答案 0 :(得分:1)

您可以启动php进程并将脚本传递给stdin,从stdout获取结果,而不是使用临时文件。

答案 1 :(得分:0)

您可能希望使用system()调用来启动PHP并运行脚本。

答案 2 :(得分:0)

我有一个替换stdin的代码:

int spipe[2];
if( pipe(spipe) == -1 )
    return 0;
int pid = fork();
if( pid == -1 )
    return 0;
if( !pid )
{
    close(spipe[1]);
    dup2(spipe[0], 0); //dup2(spipe[0], stdin);
    if( execl(PROGRAM_NAME, PROGRAM_NAME, PROGRAM_PARAM, NULL) != 0 )
        exit(1);
}
close(spipe[0]);

您可以用相同的方式将stdout替换为另一个管道。