Skip to content

Instantly share code, notes, and snippets.

@beberlei
Created January 14, 2012 18:21
Show Gist options
  • Save beberlei/1612340 to your computer and use it in GitHub Desktop.
Save beberlei/1612340 to your computer and use it in GitHub Desktop.
ZeroMQ Server (REQ-REP) that embeds PHP
cd /path/php-5.3.9
./configure --enable-embedd
ln -s /path/php-5.3.9/libs/libphp5.so /usr/lib/libphp5.so
ldconfig
g++ -o zmqembed zmqembed.c -I/path/php-5.3.9 -I/path/php-5.3.9/main -I/path/php-5.3.9/Zend -I/path/php-5.3.9/TSRM -L/path/php-5.3.9/libs -lphp5 -lzmq
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sapi/embed/php_embed.h>
static char * s_recv (void *socket) {
zmq_msg_t message;
zmq_msg_init (&message);
zmq_recv (socket, &message, 0);
int size = zmq_msg_size (&message);
char *string = malloc (size + 1);
memcpy (string, zmq_msg_data (&message), size);
zmq_msg_close (&message);
string [size] = 0;
return (string);
}
int main(int argc, char *argv[])
{
zend_file_handle script;
if (argc != 2) {
fprintf(stderr, "Usage: zmqembed filename.php\n");
return -1;
}
if (!fopen(argv[1], "rb")) {
fprintf(stderr, "Unable to open %s\n", argv[1]);
return -1;
}
argc--;
argv++;
void *context = zmq_init (1);
// Socket to talk to clients
void *responder = zmq_socket (context, ZMQ_REP);
zmq_bind (responder, "tcp://*:5555");
PHP_EMBED_START_BLOCK(argc, argv)
while (1) {
// Wait for next request from client
char *request = s_recv(responder);
// Do some 'work'
script.type = ZEND_HANDLE_FP;
script.filename = argv[0];
script.opened_path = NULL;
script.free_filename = 0;
if (!(script.handle.fp = fopen(script.filename, "rb"))) {
fprintf(stderr, "Unable to open %s\n", argv[1]);
return -1;
}
php_execute_script(&script TSRMLS_CC);
// Send reply back to client
zmq_msg_t reply;
zmq_msg_init_size (&reply, 5);
memcpy (zmq_msg_data (&reply), "World", 5);
zmq_send (responder, &reply, 0);
zmq_msg_close (&reply);
}
PHP_EMBED_END_BLOCK()
// We never get here but if we did, this would be how we end
zmq_close (responder);
zmq_term (context);
return 0;
}
@beberlei
Copy link
Author

This currently does not really transfer data from the server to the php script and back to the client. Its just a prototype to check if it would work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment