Is it possible to have a C++ program running on a server that sits and waits to be passed arguments by a PHP process.
The C++ program would then process these arguments and return a result to PHP.
I’ve been searching the web and can see a couple of ways to run a C++ program from PHP but can’t find a way to interact with a C++ program that is already running.
The sort of C++ programs I’m thinking of are ones that might take time to set up e.g. They create a big data structure of some kind and so I don’t want to run them every time I need them. I want the C++ programs to create their data structures and then sit back and wait until asked by PHP for information from that data structure.
Thanks
Use named pipes.
https://web.archive.org/web/20140223054156/http://my.opera.com/zomg/blog/2007/08/29/php-and-named-pipes
and
C++ https://web.archive.org/web/20110926155246/http://ist.marshall.edu/ist480acp/namedpipes.html
Write a C++ listener that recognizes XML RPC or SOAP requests so it can process the requests natively and return the results to PHP as an XML RPC or SOAP response.
Here are some references:
http://xmlrpc-c.sourceforge.net/
http://www.cs.fsu.edu/~engelen/soap.html
Would something like SWIG be of use to you? (http://www.swig.org/Doc1.3/Php.html) You could wrap the functionality you want to use, to expose it to your PHP code.
Related
Building a PHP script that responds to an Ajax request is as easy as:
<?php
$command = $_POST["command"];
if ($command == "say_hello") {
$name = $_POST["name"];
echo json_encode(array("message" => "Hello, " . $name));
}
?>
and, at least if you're using jQuery on the client side, and if you specified a callback function on the original request, the array containing the message will be passed into that callback function.
But with Python it's not that simple. Or at least I haven't figured out how to make it that simple. If I just try to "print" a response (paralleling PHP's "echo" statement above) the client doesn't get anything back.
Whenever I've looked on the internet for how to respond to an Ajax request with Python, the answer always involves using Django or some other web framework.
And I know those things are great, but what is PHP doing that makes using a similar package unnecessary? I would like to be writing my server-side script in Python instead of PHP, but I'd prefer a D.I.Y. approach to using a third-party framework for what should be (right?) a pretty simple task.
Any help? An example of how to do this would be much appreciated.
But with Python it's not that simple. Or at least I haven't figured out how to make it that simple. If I just try to "print" a response (paralleling PHP's "echo" statement above) the client doesn't get anything back.
I might have some of the details wrong, but I'll try to explain why this is the case. Firstly, the PHP you're talking about is baked directly into the apache webserver. When you do an echo, it outputs the result to the response stream (a TCP connection between the server and client). When you do print in python, what you're doing is outputting the result to standard out (the command line).
How most languages work with the web, is that a request comes in to some kind of web server, and that web server executes a program. The program is responsible for returning a stream, which the webserver takes, and streams to the client over the TCP connection.
I'm assuming that the webserver redirects PHPs standard out to the webservers stream, and that is how PHP is able to use echo to return its result. This is the exception, not the rule.
So, to use python to serve requests, you need to have a webserver that can execute python in some way. This is traditionally done using CGI. More recently, something like mod_python was used to host the python within apache. Nowadays, wsgi or mod_wsgi is used, which is the standard defined for webservers talking to python.
You might want to look at something like web.py, which is a minimalist python web framework. This will get you very very close to what you're trying to do.
PHP was built with the web in mind from the very beginning. In contrast Python was designed as a general purpose language.
When you echo from PHP you're actually writing to a stream that is sent to the user as part of an HTTP response. When you do a print in python the output, by default, is written to the stdout stream which means instead of being sent to the user over http the output is written to the console (or whatever is capturing stdout at the moment).
So to PHP, HTTP is a first class citizen. To more general purpose languages like Python, Ruby, Erlang, C, C++, and so many other languages. You have to communicate to HTTP in different ways. PHP already handles that communication through apache's mod_php or through something like PHP-FPM.
Sooo....
As far as creating your own server side script, I'd highly suggest against it as Python's Frameworks take the place of the layer that PHP is built on. So creating a standards compliant http server on your own with Python isn't going to be very simple. The reason that this is so hard is that you'd either have to interface with CGI or WSGI (a Python standard for dealing with the web) or create your own HTTP server. If you think you're up to the task then I highly suggest it! You'd probably learn a whole lot by doing it, but it isn't going to be the easiest thing. The great thing is that so many libraries already take care of this communication for you. For example, if you're looking for something lightweight, I highly suggest a micro-framework like flask which is one I personally use if I need something very simple. It is much easier to get started than django, but it also has less batteries included.
Hope this helps!
There is a python module called json. Perhaps so many of the answers deal with frameworks (like Django) because json is web-centric and Django, tornado, twisted, cherrypy, etc. all are the means by which python interacts with the web.
There are many different ways to do this, and those are addressed in other questions. However, to just answer your question, python has a json library in its standard library.
Most PHP installers configure themselves by default to serve php files in web directories by running the script. Most Python installers do not. Quickest way to serve Python with apache:
In your apache config file, add AddHandler cgi-script .py to whatever block can already serve PHP files
shebang your python scripts by adding #!/usr/local/bin/python or whatever path python is on in your system
remember to print headers first, followed by a newline, then body.
use import cgi if you want to do anything more complicated than sending back a response body.
Note that this is not the recommended way to run a python website, just the fast, php-ish way.
Richardhsu has the gist of it correct.
Essentially python is a general purpose scripting language. As such, it needs a way to connect to the web, such as by opening a port and doing network programming etc. You can also use something CGI to attach to apache or other web server.
This is really no different then how Java, Ruby, Perl or C/C++ get to the web either. In fact, PHP does much the same thing. It's interface to the web server is just tighter then CGI.
If you were to have PHP interpreted from the command line, or compiled, then you would have the exact same issues that you do with Python now. The issue isn't PHP vs Python, it's how you get the scripting language of your choice attached to the internet using the HTTP protocol.
I've been looking into this for several hours, but everything I've looked at seems rather daunting. I've been using PHP for all of the simple stuff on my website so far. I'm doing a lot of statistical work, and I would like to have c++ available for the more intense calculations.
The c++ would be running locally on the same Unix machine as PHP.
Something like the following is what I'm at a loss for how to do:
<?php
//c++ program has a counter initialized to 0
//PHP tells c++ to add 5 to the counter. $incremented is 5
$incremented = increment_in_cpp_and_return(5);
//$incremented_again will be 7
$incremented_again = increment_in_cpp_and_return(2);
?>
Of course, I'm running some monte-carlo simulations and traversing really big trees instead of incrementing numbers, but that's not what's holding me back.
C++ just needs to listen for a number and return another number (maybe some stuff in JSON at most). It is important for the c++ to keep track of its variables between calls.
I've done a lot of reading on TCP, socket programming, etc and I'm just a little doubtful that this as complicated as the examples make it out to be. A lot of things have pointed me to this https://beej.us/guide/bgnet/html/multi/clientserver.html#simpleserver
If it really is more than 100 lines of c++, are there some popular libraries, or is there a simple implementation in another language?
Thanks!
If you only want to access your C++ program from PHP (or use PHP as the web frontend for your C++ code), an alternative to communicating over a socket would be to embed the C++ code into PHP as an extension.
There's a fair amount of boilerplate code associated with it, but most of it is generated for you by the ext_skel script (included in the PHP source).
Most information online about writing PHP extensions relates to using C, see Extending PHP with C++? for a couple of gotchas related to using C++ for this.
If your C++ is executeable, you could open it as a program, pass data to it via STDIN and pass the return value back to PHP via STDOUT. See proc_openDocs.
Your standard C++ library should offer access to STDIN and STDOUT, so you already have what you need.
I'm a little confused about how the c++ keeps its state between calls. Can proc_open be used to pass via STDIN to a c++ program that is continuously running? I'm worried that it starts a new instance of the c++
You might be looking for a Named pipeWikipedia, a form of inter-process communication (see as well: What are named pipes?), that is supported by most operating systems. It's simple I/O (FIFO) and similar compared to STDIN and STDOUT. You can keep your executable in memory while the other processes can send data to it.
Another simple way is to use sockets, those are supported by PHP as well and should be with your C/C++. Sockets will work across different machines, so you can run your (memory/CPU intensive?) own executable on a dedicated server that does only the calculation for example. Just looks what suits better in your case, from the comment I read you're looking for interprocess communication.
posix_mkfifoDocs (including sample PHP code in user-notes)
Sockets Tutorial - a simple tutorial on using sockets for interprocess communication (Linux Howtos)
Introduction to Named Pipes (Linux Journal)
Introduction to Interprocess Communication Using Named Pipes (Sun Developer Network)
(these are just some resources, you naturally can find more with a little research, I think for both named pipes and sockets you should be able to find source-code examples for your case)
You could try:
exec()
You send the data from PHP as arguments for the C++ written program that will be executed and the program will return the output so you can use it in PHP after the C++ program's execution.
I've been using gSOAP for remote procedure calls between C++ and PHP, and if you're using PHP5, the interaction is made very easy; see http://www.php.net/manual/en/class.soapclient.php
I'm in the process of analyzing a large chunk of data in matlab. The data is userdata which is freely available and which I want to use to make recommendations for users using my Internet service.
My question is: once I've written my algorithm in matlab what is the easiest/best way to integrate it into my php project /website?
Thanks in advance
Well, it really depends on what you are using Matlab for. In many ways, doing the same matrix transforms in PHP or Python would be a pain. Hence you were using Matlab. You can however keep everything in Matlab form by using the Matlab Web Server.
Simply compile down to a binary that can be run on your server. See the examples supplied by Matworks.
I am working on a PHP project that makes use of MLB's Gameday data. There appears to be a pretty solid Ruby library for working with data. I don't particularly want to rewrite the entire library in PHP, so I was wondering if anyone had any suggestions for a good way to interact with the Ruby scripts from my PHP application.
I'm starting to think that I'll need to write some sort of command line Ruby script that'll interact with the Ruby classes and output the data in a format usable by PHP (JSON, XML).
Are there any better ways to do accomplish this?
Another option is to use Gearman, written by the the same team that brought us memcached. It has PHP and Ruby bindings.
You'd create a daemon in Ruby that exposes functions to Gearman, then have your PHP code call those functions through Gearman. No Apache needed.
(Boy, I'm on a Gearman plugging streak. I wish I was getting paid for it!)
Rather then a command line interface, I'd suggest outputting data in JSON format and requesting that data via PHP & CURL.
If you needed to you could even write a REST interface for it pretty easily.
I'm new to PHP. I am familiar with ASP.NET which support asynchronous programming. That is, if one request needs to do some I/O job. It is suggested to program the web page with BeginProcess/EndProcess way. The asynchronous programming is key to improve scalability.
I'm wondering whether there is counterpart of asynchronous programming(BeginXXXX/EndXXXX) in PHP world.
In .NET BeginXXX/EndXXX paradigm relies heavily on threading, while on PHP I am not sure that you could even start a new thread (except maybe the PECL package).
FastCGI is the alternative to multithreading in most interpreted languages. Instead of spawning new threads it uses processes, but as spawning a new process is expensive, it keeps a reusable process pool just as the ThreadPool in .NET.
If the I/O is performed with sockets or files you should use stream_socket_select() or stream_select() respectively (similar to system calls in C/C++).
Here's a simple command line chat tutorial done with PHP:
Simple PHP socket-based terminal chat
Note: This is not a general multi-threading solution, but a simple solution for situations where you need "semi-parallel" I/O
The core has a set of process control functions, including the ability to fork a process.
I don't know that I'd use these in a web script, but have used them in command line scripts before.
http://www.php.net/manual/en/book.pcntl.php
http://www.php.net/manual/en/pcntl.example.php
Here's an interesting link on the subject of PHP multiplexing with PHP4 and PHP5 samples:
http://netevil.org/blog/2005/may/guru-multiplexing
PHP doesn't, but you could use AJAX once the page has loaded, which will allow asynchronous requests.
Honestly though, there is no point. If you really want that heavyweight of a back end, you're better off writing a separate program that does the heavy lifting. PHP modules are written in pure C as far as I'm aware, so you should be able to use that and then call your own custom function from PHP.
Using stream_select you can create child processes via a HTTP request. Checkout the code in http://drupal.org/project/httprl for some ideas on how to do this. I plan on pushing this library to github once I get it more polished; something that can be ran outside of drupal. But for now it lives in Drupal land.