How to set up communication between PHP and C++? How to set up communication between PHP and C++? apache apache

How to set up communication between PHP and C++?


I think the easiest way is:

1) PHP -> C++ : tcp

2) C++ -> PHP : http

Will try to explain.

1) To take something from C++ app PHP connects to that app using stream_socket_client function. C++ app is listening on host and port using socket, bind and listen functions. As soon as connection arrives C++ app accept it and then in a separate std::thread serves it (recv to get request, send to send response). How to socket.

2) As PHP is working under Apache Web Server, I think the easiest way is use of libcurl library to make HTTP request from C++ app. How to curl.


Another approach could be SOAP or REST Web Services. On both sides, you could provide a SOAP Web Service to exchange data or to call remote functions. On C++-side, you could use Apache Axis to provide a SOAP Server. On PHP side, you can use the build-in SOAPServer class (http://php.net/manual/de/class.soapserver.php).

With SOAP you simply would exchange XML-based messages between both applications over HTTP / HTTPS. With this approch, both applications can trigger each other and exchange data.


Adding to the answer of Ben Schnarr, I think probably the most elegant and easy solution would be to make the C++ program a client for web services implemented in the PHP code. Using sockets directly would force you to have an additional protocol over it to represent the data being transmitted (unless the data is trivially simple, like a stream of ASCII text), which would be a bit like reinventing the wheel.

I'm partial to REST+JSON, because they are simple to implement and use, and very powerful. In contrast, SOAP is quite complex, heavy in resources, and brittle, especially if you use it with C++. One popular implementation I've already used, for instance, would force you to recompile your code every time you change the layout of any of the messages, even if the server is adding a field that the client won't use.

On the PHP side, it's quite easy - it already has all the infrastructure you need. On the C++ program, the minimum you'll need would be an HTTP client library and a JSON codec. I use libcurl for the first (by far the most popular) and jsoncpp for the latter, but there are other options for both. More recently, some libraries appeared with the whole package, but I hadn't had the chance to use them yet. Some examples:

restclient

REST SDK

Restbed