7

Could some one explain me how to run a C program from a php script and store console output of the C program to a php variable?

My program prints an integer value on the console using C printf() function. I want to read this value and store it in a php variable.
I am using linux. I tried exec but it doesn't display the variable value once echoed to the page

This the code snippet I am using.

exec("Release/matchface image1.jpg image2.jpg", $output);
while( list(,$row) = each($output) ) {
  echo $row. "<br />";
} 

1 Answer 1

13

You'll want to use the shell_exec() function (quoting) :

Execute command via shell and return the complete output as a string

Which means something that will look like this :

$output = shell_exec('/path/to/your/program');

Or, you could use the [**`backtick operator`**][2] -- which would do exactly the same thing *(quoting)* :

PHP will attempt to execute the contents of the backticks as a shell command; the output will be returned

And, in code :

$output = `/path/to/your/program`;
Sign up to request clarification or add additional context in comments.

6 Comments

this doesn't print anything on browser.
Even if you use echo $output; ? Are you sure your C program is echoing on stdout ?
Yep it does. I ran it in terminal using exact parameter parsed to exec() and it prints an integer.
@Niroshan: That doesn't necessarily mean it's printing on STDOUT. It could be printing on STDERR. And make sure your path is correct. Don't forget that the environment is different.
I know it's not the case in this example, but just a word of caution: if you ever take arguments from a user in the shell_exec(), you should strongly consider using the escapeshellcmd() function (e.g. shell_exec('ls -latr ' . escapeshellcmd($arg);) otherwise, if the user-entered field arg is '; rm *.*' they'll remove all your files, or inject any code they wish...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.