C++ – Passing variables from PHP to C++

cjunior-programmerPHP

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.

Best Answer

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 https://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:

<?php

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 https://stackoverflow.com/questions/1746207/how-to-ipc-between-php-clients-and-a-c-daemon-server

Related Topic