PHP to C/C++ through CGI script - php

I realize it's probably something strange, but here is what I have.
I have an application (handwriting recognition engine) written in C/C++. This application has Perl wrapper which was made by application's authors using SWIG. My website is written in PHP, so I'm looking for some ways to make PHP work with C/C++ application.
The only way I can think of now is to create a CGI script (perl script) which accepts POST request from my website (AJAX request), sends it to the recognition engine through it's Perl wrapper, gets the required data and returns the required data as a response to AJAX request.
Do you think it could be done this way? Are there any better solutions?
Thank you!

Do you think it could be done this way?
Yes, no reason it can't be done.
Are there any better solutions?
May be. If you intend to execute the perl wrapper as a system call to a separate Perl script, you don't need a separate CGI perl script. You can just do system calls from PHP in your site directly. Not a big difference but might help if PHP is more of your comfort zone for web stuff than Perl's CGI
OTOH, if the Perl script wrapper is a fairly obvious and simple set of API calls, and you feel comfortable with Perl CGI, a better soltrion is to port that command line Perl script into the Perl CGI script which uses the API internally, bypassing system calls.
For high-volume stuff, removing system calls is a Big Win performance wise, plus allows for much better and easier error handling.

What you are proposing is:
web client <-> Perl CGI script <-> Perl wrapper <-> C program
There is nothing particularly wrong with this approach, although it's clearly not the most efficient possible way to do it. How important is performance? If it's doesn't have to be amazingly fast, sure do it this way, which sounds like it's the easiest to develop.
If you want to go a step further, then the obvious point of optimization in the schematic above is to collapse the two Perl layers:
web client <-> Perl CGI script <-> C program
The question is, is it worth your time to do this? You can look at the source for the Perl wrapper and decide for yourself.
My advice would be to initially develop it the simple way and then if, for whatever reason, you decide it is insufficient, to merge the two Perl scripts into one. But for now, don't worry about it and go ahead with your idea.

Related

Why does PHP just work with Ajax but Python doesn't?

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.

Haskell web applications using PHP as a "front end"

There have been great things happening in the Haskell web development world, and some of the available frameworks (Yesod and Snap server) seem quite mature. However the learning curve can be a bit steep, and perhaps building web apps cannot quite be considered Haskell's forte.
The answer to another SO question of mine indicates that writing PHP extensions in Haskell should be possible. Infact I'm currently in the process of trying to convert a small Haskell program to a PHP extension as a proof of concept.
So, the question is - is there a case for creating a Haskell web framework that is meant to be run as a PHP extension and leaves all the request/response / cookies etc. handling to PHP?
What would be the design decisions involved in creating such a framework? Right now, the only thing I can think of is that it would probably expose an XML/JSON API accessible by the PHP pages using GET and SET function calls.
I can't think of a use case where this makes any sense. If you want something else to handle the HTTP request/response, you'd be better off writing to the Apache API directly.
Introducing PHP gives you argument parsing and cookie handling but also introduces a lot of other silliness. Not only are many of the common practices very unsafe or insecure, but you are limited to content generation -- if you want to dispatch to other parts of code based on the URL you have to write all that yourself. Many mature PHP programs end up just having one "start" PHP script. You also will have problems if you want to do anything interesting with uploaded files, because PHP handles that in a suboptimal way.
You could theoretically do something very processor intensive in your Haskell extension, but you might as well just write a C extension for PHP in that case. And PHP invocations are never supposed to hang around for very long anyway.
Seems like you are limiting yourself to PHP's brain-damaged model of a web application for the very trivial benefit of argument and header parsing.
Writing a Haskell interface to the Apache API could potentially be liberating. You could rely on a battle-tested web server, and also hook into every phase of the Apache request cycle. Apache's way of preforking and killing children every now and then might be a way of dealing with Haskell space leaks, although it's a sledgehammer approach.

PHP without a server

I have a C# application that needs to call a PHP script, and get the output, in the fastest possible way. The options I explored:
Executing the script with PHP CLI (Pro: Easy / Cons: No Opcode Cache / Precompilation ]
Compiling the PHP (Phalanger, Hiphop, etc.) [Pro: No Webserver / Con: Compatibility ]
Using an embedded webserver (AppWeb, Cherokee, Lighttpd) [Pro: Simple / Cons: Deployment ]
Are there any other options left?
EDIT: The best possible option would be to make use of the build-in FastCGI server of PHP, by running php-cgi.exe -b 127.0.0.1. But there seems no (C#) code to talk to a server available. While there are so many server-side libraries (like FCGIDotNet and SharpCGI), they all implement the server-side of the protocol.
One other option could be to run the PHP CLI script as a daemon (good blog post on this here).
If the script has a particularly long startup/cleanup, then running it as a daemon would mean that you only do this once.
The downside is that you'd need to write a way of communicating with that daemon, to get the data from C# to it. You'd also need to keep an eye out on its memory usage over time.
The best method is always going to be specific to your script though.
As you may know, PHP originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext Preprocessor", which literally states it's usage, and basically is not something that a developer would embed into his application just to have a scripting option.
Unless you have some really specific piece of software and strong arguments, I'd suggest you to stick to Lua, or similar scripting libraries which are easy to embed and maintain. Otherwise, use it the way as everyone is using it, CLI. Or else be prepared to face the consequences.

PHP-style web development on Ruby: creating microframework for that

In PHP world you can just create index.php file, put some inline code and raw HTML, run Apache and it just works.
There are a lot af talks about bad practices of using inline code an so on. So we won't discuss this theme here, please.
How can I start my Ruby application same way? I want to use ERB for code messing, so it will look this way
# index.rb
<h1>Hello world!</h1>
<div>
1 + 1 = <%= 1 + 1 %>
</div>
So my questions are:
What makes PHP just work.
AFAIU(nderstand) There is native support for HTTP in PHP, so I have to use Rack to support it with Ruby
Some basic knowledge for creating my on "microframework": working with application/http servers (Mongrel, nginx, binding on http port and all such kind of job), working with HTTP requests: sessions, params, GET/POST etc (Rack?), sending responses (ERB templating).
So I can make my own (in educational puprposes) microframework for PHP-style web development with Ruby :D
UPD
What really I want to do is an application wich will just get request url, run just that file and return HTML as a response. Also this application should be allowed to be binded on some port
index.rb
info/about.rb
info/contacts.rb
products/product.rb
so It should parse url localhost/index.rb and run index.rb, localhost/products/product.rb?product_id=10 and run products/product.rb and pass product_id=10 as a params hash.
UPD 2
I think good point to start is to dig into Camping microframework source:
https://github.com/camping/camping
It is about 5Kb weight so I shouldn't be confused in it
It is possible to write CGI scripts with Ruby but this is generally not done because we have better solutions.
One file per page is not a very useful abstraction, it's just the one that PHP supports. Ruby has better ways to abstract a web application (like Sinatra, Rails, or even just Rack) so we prefer to use them.
Putting the file name in the url is another unfortunate side effect of PHP's design. It is implementation revealing and unnecessary (you're not getting a Ruby page, you're getting an HTML page), so we choose not to do that either.
CGI and FCGI in Ruby are also slower than the other solutions. This is not because of some limit on how performant they can be; it's mostly just because the effort to make Ruby web applications faster has been spent in more useful areas like Rack and Rails. No one really uses CGI so no one really cares to make it fast. mod_ruby makes CGI scripts somewhat faster if you really want to go this route, but again: there are better ways.
Apache can run PHP by loading in the mod_php module.
I believe to run ruby you will need to have it installed on the server and have mod_ruby loaded into apache. take a look at: http://www.modruby.net/en/
You are looking for CGI. The Apache modules like mod_php or mod_ruby are just packaging provided for CGI scripts written in PHP or Ruby.

Does PHP support asynchronous programming?

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.

Categories