Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a question regarding the titled question. So, I'm attempting to create a program which passes data/requests for data between a program in C++ and a PHP site running off of an Apache web server.

I've been researching Socket communications, but I'm not understanding the concept. I understand how to create a socket in PHP, and another in c++, and I have them running using a test application. But only individually, not talking to each other OR talking to my web server (the PHP is not on the server at the moment, it is on a different server). So how does this work? From my understanding, you need one to be listening to a port number, and the other one to send something to that command.

Ideally, I would prefer not to use any libraries to help me achieve this. I know this question has been asked many times before, but I'm still getting nowhere.

Could someone provide an explanation of how the above works, or links to a question on here/elsewhere that may be of help? Or if there is a better method of doing this than using sockets? They will be talking to each other a lot, and speed maybe an issue.

Edit, further explanation:

Web server: I'm running an Apache web server. The PHP script is located on this server.

C++ Location: While testing, my c++ application is stored on the same Raspberry Pi that the web server is running on. In the real application, my C++ application will still be stored on the same device (but it won't be a Raspberry Pi - still Linux based though).

Communication: The PHP script will need to be triggered to do things by the C++ script, and vice versa. They will need to both need to pass data (common data structures, but they could be fairly large) each way (so both need to be able to send and receive data).

like image 724
mfisher91 Avatar asked Oct 28 '15 21:10

mfisher91


1 Answers

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.

like image 184
stas.yaranov Avatar answered Sep 21 '22 04:09

stas.yaranov