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

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.

Related

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.

Mixing Python and PHP?

I have some Python scripts that I run on my desktop now for cutting up files. I want to put them on the web and write a simple front-end in PHP where a user uploads a file and it is passed as an argument to a python script on the web server and it is written out in chunks and the user can re-download the chunks.
I know a decent amount of PHP, but I do not see:
How to mix PHP and Python programmatically
Is it possible to have a webpage in python that can just call the python script? Can one have a GUI page that is like zzz.com/text.py as example
For http requests, you need to set your web server to hand over certain request to PHP and others to Python. From within PHP's scripts, if you need to call some Python executable scripts, use one of PHP's shell functions. e.g. exec()
Yes it is possible. The djangobook is a nice tutorial that covers this in one of the earlier chapters. It shows you how to run python as a cgi or with apache.
On a personal note, if you have time to dig deeper into Python, I'd strongly encourage you to do the whole thing in it, rather than mix things with PHP. My experience tells me that there are probably more cases where a PHP app needs some Python support rather than the reverse.
If the supporting language can do everything that the main language does, what's the point of using the main language?

PHP to C/C++ through CGI script

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.

PHP complex uses - Interact with external devices

Is it possible to access & control external devices in PHP?
For example, would it be capable of changing the speed of a USB fan or change the direction of a wireless toy car.
I'm trying to go beyond web dev and I'm wondering if the programming language I use is capable of handling my ideas or should I consider changing the environment.
If these would be possible, I'd very much appreciate any pointers to reading materials or suggestions on other languages that might be more suitable.
Thanks!
On Linux it surely is possible by accessing /dev/ files. But it'll be very tedious. I'd recommend you switching to Python, Ruby, Lua or Java.
For example there are bindings for libusb for Python, Ruby, Lua and Java.
You could write an external program, then use PHP's exec (or was it system?) function to interact with the executable or script.
Seems like the most sane way to do it. Another good alternative is to build a program or script that controls an external device that can communicate with a RESTfull type API exposed via HTTP - and then use lib_curl in PHP land to talk back and forth between it. Believe me, building a basic HTTP server in C++ that can be used to be remote controlled with PHP (or JS for that matter) is very simple.
Wait
I think I read the question wrong ;)
If you want to get into really cool stuff, I say that you learn C++. C++ is a great language that not only opens a lot of doors, but also provides a good learning experience. C++ is lots and lots of fun.
In response to comment
In the case with USB its a bit different and more complicated (as USB has an established protocol and such) but serial is as easy as dumping data into a handle.
You should be able to pick up C++ to get to that point fairly soon. Either way it's a great experience.
This would be possible with a extension, but not with pure PHP code. I don't know of any extensions being able to do something like this, but I think it should be possible.
If you find a command line tool that does this, then you can control it using exec(), system(), passthru() or shell_exec() (based on what output the program gives you back)
Just be sure to escapeshellcmd() if you give access to this program from a public website.

Categories