Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a C program from php and read program output

Tags:

c

linux

php

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 />";
} 
like image 775
Niroshan Avatar asked Apr 05 '11 17:04

Niroshan


People also ask

Can we use PHP to write command line scripts?

There are two variables you can use while writing command line applications with PHP: $argc and $argv. The first is the number of arguments plus one (the name of the script running). The second is an array containing the arguments, starting with the script name as number zero ($argv[0]).

How to GET command line arguments in PHP?

There are two predefined variables in PHP, called $argc and $argv , that you can use to work with command-line arguments. The variable $argc simply tells you the number of arguments that were passed to the script. Remember that the name of the script you are running is always counted as an argument.


1 Answers

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 -- 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`;
like image 128
Pascal MARTIN Avatar answered Sep 21 '22 06:09

Pascal MARTIN