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.
Related
Guys recently I decided to go back to PHP and do some more complex stuff than a simple log in page. For 3 years I've been programming with Java/JavaEE and have a good understanding of the architecture of of Java Applications. Basically, a virtual machine ( a simple OS process ) that runs compiled code called byte code. a simple Java web server is basically a java application that listens on provided TCP port for Http requests and responds accordingly of course it is more complicated than that but this is its initial work.
Now, what about PHP ? How does it work ? What, in a nutshell, is its architecture.
I googled about this question but in 90% the articles explain how to implement and construct a web application with PHP which is not what I am looking for.
The biggest difference between a Java web server and PHP is that PHP doesn't have its own built-in web server. (Well, newer versions do, but it's supposed to be for testing only, it's not a production ready web server.) PHP itself is basically one executable which reads in a source code file of PHP code and interprets/executes the commands written in that file. That's it. That's PHP's architecture in a nutshell.
That executable supports a default API which the userland PHP code can call, and it's possible to add extensions to provide more APIs. Those extensions are typically written in C and compiled together with the PHP executable at install time. Some extensions can only be added by recompiling PHP with additional flags, others can be compiled against a PHP install and activated via a configuration file after the fact. PHP offers the PEAR and PECL side projects as an effort to standardise and ease such after-the-fact installs. Userland PHP code will often also include additional third party libraries simply written in PHP code. The advantage of C extensions is their execution speed and low-level system access, the advantage of userland code libraries is their trivial inclusion. If you're administering your own PHP install, it's often simple enough to add new PHP extensions; however on the very popular shared-host model there's often a tension between what the host wants to install and what the developer needs.
In practice a web service written in PHP runs on a third party web server, very often Apache, which handles any incoming requests and invokes the PHP interpreter with the given requested PHP source code file as argument, then delivers any output of that process back to the HTTP client. This also means there's no persistent PHP process running at all times with a persistent state, like Java typically does, but each request is handled by starting up and then tearing down a new PHP instance.
While Java simply saves persistent data in memory, data persistence between requests in PHP is handled via a number of methods like memcache, sessions, databases, files etc.; depending on the specific needs of the situation. PHP does have opcode cache addons, which kind of work like Java byte code, simply so PHP doesn't have to repeat the same parse and compile process every single time it's executing the same file.
Do keep in mind that it's entirely feasible to write a persistent PHP program which keeps running just like Java, it's simply not PHP's default modus operandi. Personally I'm quite a fan of writing workers for specific tasks on Gearman or ZMQ which run persistently, and have some ephemeral scripts running on the web server as "frontend" which delegate work to those workers as needed.
If this sounds like a typical PHP app is much more of a glued-together accumulation of several disparate components, you'd be correct. Java is pretty self-contained, except for external products like RDBMS servers. PHP on the other hand often tends to rely on a bunch of third party products; which can work to its advantage in the sense that you can use best-of-breed products for specific tasks, but also requires more overhead of dealing with different systems.
This is how does PHP work:
(one of the best over the Internet)
In general terms, PHP as an engine interprets the content of PHP files (typically *.php, although alternative extensions are used occasionally) into an abstract syntax tree. The PHP engine then processes the translated AST and then returns the result given whatever inputs and processing are required.
Below image will depict more information
Source: freecodecamp.org
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 have a set of ~5 ActionScript 3 classes that are currently used within a flex 4 application. Although their output is used to display graphs etc in my flex app, the classes themselves have no visual components - they are only used to do complex math computations (I originally implemented them in AS3 in order to avoid constant server calls when computations were needed by the flex app).
However, I now want to make the same mathematical computation engine available on my linux server so the computations can be done within PHP. Is there any way at all to access the logic in these classes on the server? I would really like to avoid re-implementing the complex logic in PHP.
Thanks so much for any help you can give!
How many lines of code in your AS3 classes, and what kind of load do you need to handle?
If you're building anything for more than one-off use then the easiest route is probably porting your ActionScript to JavaScript. There aren't any automated converters that I know of but JavaScript and AS3 are so similar that unless your five classes have thousands of lines of code you should be able to make short work of it. Once you've ported it to JavaScript it'll be trivial to run in Node.js, directly through the VM of your choice, or even in the user's browser.
If you only need this to scratch and itch or for limited use you may be able to get away with running AS3 directly in Tamarin or redtamarin. However as far as I know neither of these are currently suitable for production use.
If you are using this in a high-availability, high traffic PHP app, however, I think you'll experience a lot less pain in the long run just porting your code to PHP. AS3 and PHP are similar enough in syntax that you could probably just do a straight port.
Finally, you can find some further discussion and links in this thread: Is it possible to create a 'command line' swf?
You can use redtamarin
http://code.google.com/p/redtamarin/
from a Linux server standpoint you will be able to run
your AS3 source code as CGI (either the AS3 script directly or compiled as ABC)
or you can also bundle your AS3 code into an exe that you will then call via PHP
or make your AS3 script as executable with binfmt_misc
http://code.google.com/p/redtamarin/wiki/RunningShellScripts#Registering_an_extension_as_non-native_binaries_(Linux_only)
here on production and development servers we use redtamarin
as scripts, to do our SVN hooks, automate tasks on linux servers etc.
as socket servers, http servers and CGI
as executable to reuse AS3 logic into our automated builds
etc.
look a bit in the documentation you will see you have a lot of options
to reuse your AS3 code: stdin/stdout/stderr, sockets, pipes, CGI, etc.
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.
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.