Retrieving the output of a C program using a PHP script

B

Ben Chivers

I have a problem, which I think can be easily solved somehow.

I am trying to execute a C program through using a PHP script. I do
this by sending an exec command from the PHP script. My PHP script is
printed below:

<?php

system('main.exe');

?>

When I execute my PHP script, it only prints 'Hello World', and not
the output of the buffer in the C program. My C code is shown below:

#include <stdio.h>

int main()
{
printf("Hello World\n"); /* this prints fine on the php script */

char buffer[1024];

FILE *pipe;
pipe = popen("php -f testing.php", "r"); /* executing the php file
'testing.php' via the command line */
fread(buffer, 1, 1024, pipe);
printf("%s", buffer); /* this prints the output of the execution of
the PHP script */
pclose(pipe);

return 0;
}


Why does it do this? Is there a way around this issue?

If you execute the C program via the command line, the output of the
PHP script prints fine.

Any help with this issue would be most appreciated.

Many Regards,
Ben Chivers
 
A

Alexander Bartolich

begin followup to Ben Chivers:
FILE *pipe;
pipe = popen("php -f testing.php", "r");
fread(buffer, 1, 1024, pipe);

Oops. Evil. What of popen failes and returns zero?
printf("%s", buffer);

Ugh. Not only is this lame, it's also wrong.
Who says that the output of a PHP-script will be 0-terminated?
fread itself will definitely not append the zero.

pipe = popen(...);
if (pipe != 0)
{
size_t len = fread(buffer, 1, sizeof(buffer), pipe);
fwrite(buffer, 1, len, stdout);
pclose(pipe);
}

For debugging purposes you might also print the value of 'len'.
[...]
Any help with this issue would be most appreciated.

Get a clue. Seriously. You seem to program by trial-and-error.
Read the manual instead, check return values, try to think of ways
it can possible go wrong.

Do you know the absolute path of php.exe? Why not?
How does the shell (cmd.exe/command.com) find it?
Does your web-server provide the same environment to CGIs?
What about dumping _environ? Or at least selective getenv?
 
M

Mark A. Odell

begin followup to Ben Chivers:

Oops. Evil. What of popen failes and returns zero?

What if popen() isn't part of C?
Ugh. Not only is this lame, it's also wrong.
Who says that the output of a PHP-script will be 0-terminated?
fread itself will definitely not append the zero.

Also, we need to ensure that we terminate with a '\n'.
[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,129
Messages
2,570,770
Members
47,329
Latest member
FidelRauch

Latest Threads

Top