It depends what you actually want to achieve, i.e. what you mean by 'connect' a c program to an index.php
?
The first thing you should realize is that what we are talking about here are two processes: (a) the c program and (b) whatever interpreter that executes the PHP script (Probably a web server).
You want to exchange data between two processes, thus we talk about Interprocess Communication.
In the Wikipedia article you see a table listing several means:
Files: Your PHP script could write to a file, the c program read from it (or, under Unix, Pipes would be even better suited)
Sockets: Just as you mentioned already, one of the programs could establish a connection via sockets and exchange their data over this connection.
- other means (have a look at the table)
Since your PHP script is probably run within a web server, the socket solution would be promising:
The web server already listens for incoming connections, and provides a decent protocol to exchange data: HTTP .
I will not repeat the answer by Basile , but just give an example for how to exchange some data between the c program and the PHP script with a web server using CGI:
The web server provides a URL, that will invoke the PHP script, like http://test.me/test.php
.
Now, the procedure would be:
- The C program establishes a TCP connection to socket test.me:80
The c program sends over a HTTP GET request by transmitting text in the form of
GET /test.php?a=31&b=19 http/1.1
The server will invoke the index.php, providing it with the key value pairs a=31, b=19
The script will do stuff, and print something to stdout like:
abc
(This is not a valid HTTP response, but its sufficient to scetch the procedure in general)
- The web server will send back the output of the php script
abc
over the connection to the c program.
As you see, in this example, you transferred
- a=31, b=19 from the c program to the web server/index.php
abc
from the web server/index.php to the c program
In general, the best solution depends on what you want to accomplish. I assume your example is just an example, and you could solve it the way I drafted above. However, if you really just wanted to have something printed to your console, just have your index.php write it to a file/pipe and the c program read the file...
This way or the other, I feel there is much for you to explore ...
Furthermore, I want to clarify one last thing:
I used 'c program' for the sake of simplicity, but i need not be a c program, but your problem referrs to an arbitrary process, it could also be a python script run by the python interpreter or ...