Take the 2-minute tour ×

I need to call a program from PHP and pass some vars and/or sets of key-value pairs to it. How do I pass these vars, through arguments to the called function?

exec("/path/to/program flag1 flag2 [key1=A,key2=B]");

Or is there a better method to achieve this? Somebody suggested to me to write them into a txt file and pass the path to it to as an argument instead,

exec("/path/to/program path_to_txt_file);

but I’m not to excited about this method.

share|improve this question
could probably just pass in a single serialized argument (like querystring style) and parse it in your c++ application... –  WebChemist Oct 10 '12 at 9:13
Is that for Unix like? When you pass arguments in the commandline, they are visible to others who do ps ax. Another possibility could be that you write strings terminated with \n to the program's fd 0 or to a fifo. –  ott-- Oct 10 '12 at 11:04
@ott-- Yes, Linux environment. –  Alex Oct 10 '12 at 11:12
Is it just me, or should this be on StackOverflow? –  DaveRandom Oct 10 '12 at 11:13
And FWIW, if you have a lot of data to pass you should write it to the child process' STDIN. The most flexible way to do this from PHP is with proc_open(). If you need to pass complex data (e.g. some vector type) you should use a standard serialisation mechanism such as JSON. –  DaveRandom Oct 10 '12 at 11:17
show 2 more comments

2 Answers

There are several ways that come to mind: doing Inter-Process Communication, building a C++ PHP extension/dll, or directly using the CLI.

You can have your PHP scripts take in shell parameters as you are suggesting (see http://stackoverflow.com/questions/6763997/shell-run-execute-php-script-with-parameters). You can evolve this to passing a single argument in the form of a query string, taking $argv[0] and set it to $_GET or $_POST, or whatever you prefer. Test it with something like:


parse_str($argv[0], $_POST);

Finally, for a more "correct" solution (using socket based communication), you might want to take a look at Thrift. See http://stackoverflow.com/questions/1746207/how-to-ipc-between-php-clients-and-a-c-daemon-server

share|improve this answer
I’m trying to execute the C++ program called from PHP, not the other way around (as in your first link example). The C++ needs take the parameters. –  Alex Oct 10 '12 at 9:22
add comment

You can echo out the variables in php and read the returned data from the HTTP request . After sending your request, you can probably use InternetQueryDataAvailable to get the number of bytes coming back, allocate a buffer large enough to accommodate the data, and use InternetReadFile to get the data into the buffer.

share|improve this answer
add comment

Your Answer


