Invoke Python API from PHP - php

how i can reproduce the same thing in PHP:
import xmlrpclib
s = xmlrpclib.Server("http://domainname.com/Verify.py", verbose = False)
print s.verify({"var1" : "test","var2" : "A" })
print s.verify({"var1" : "test","var2" : "H" })

XML-RPC is nice because it's language agnostic. As long as XML-RPC libraries are provided by a language, we can use that language. Assume A is your local machine and B is the server. In your example, both A (client) and B are running Python.
The official PHP api for XML-RPC can be found on the php site. However, i it's pretty bare since there's no documentation. I recommend grabbing the code from this repo: https://github.com/gggeek/phpxmlrpc/ which has much better documentation. So, to answer your question, we just need to two things:
Set up client to query the server
Call server to get result
Converting your code sample to PHP would then look something like:
$client = new xmlrpc_client("/Verify.py", "http://domainname.com", 80);
$message = new xmlrpcmsg("verify",
array(new xmlrpcval(test, "string")));
$response = $client->send($message);
$result = $response->value
Just for fun, let's reverse things... Now assume that you want to call a PHP function on the XML-RPC server using Python. In other words, A is running Python and B is running PHP.
import xmlrpclib
# Create an object to represent server.
server = xmlrpclib.Server("http://domainname.com/functions.php");
# Call the server to get result.
result = server.functions.multiplyAndDivide(20, 4)
print "Product:", result['product']
print "Quotient:", result['quotient']

Related

Using F# scripts like php instead of with asp.net core

So I was wondering if you could use F# with fsi.exe to run server side scripts to serve html pages. Basically, could you use it like php? If you can, would it be very practical to use it like that? Also, even if this is not very practical, I would be interested in if this would somehow be possible.
PHP and for that matter Classic ASP pages on a web site typically map one-to-one to script files on the file system on a web server.
If you implement ASP.Net's IHttpHandler you could execute F# scripts on the file system in response to HTTP requests. The IHttpHandler's ProcessRequest method passes a HttpContext instance which could be used for reading the Request arguments and setting the Response. This could be passed to a well-known function implemented, say "handler", in the F# script.
type HttpHandler() =
interface IHttpHandler with
member this.ProcessRequest(context:HttpContext) =
let localpath = context.Server.MapPath(context.Request.FilePath)
let a = compile localpath // where compile creates an assembly from an fsx file
let mi = getHandler a // where getHandler gets a function using reflection
mi.Invoke(null, [|context|])
The F# Compiler Services provides FSharperChecker API which could be used to compile F# script files to dynamic assemblies.
let compile path =
let checker = FSharpChecker.Create()
let errors, exitCode, dynamicAssembly =
checker.CompileToDynamicAssembly([| "-o"; path; "-a"; path |], execute=None)
|> Async.RunSynchronously
dynamicAssembly
The dynamic assemblies could then be used to invoke functions via reflection, passing the HttpContext value.
let getHandler a =
a.GetTypes() |> Seq.pick (fun ty ->
match ty.GetMethod("handler", [|typeof<System.Web.HttpContext>|]) with
| null -> None
| mi -> Some mi
)
So that your script file might look something like this:
let handler (context:System.Web.HttpContext) =
context.Response.Write("Hello World")
Finally there are a plethora of F# DSLS for generating HTML from code, I have a simple one called FsHtml.
Giraffe with the Razor view engine might be the best fit for what you're after: https://github.com/giraffe-fsharp/Giraffe.Razor
It provides a nice way to define API routes functionally and a nice clean syntax for HTML templates.
It does use asp.net core though - I'm not sure what you're trying to achieve by avoiding this so apologies if my answer is a little off-target.
You can compile .fsx scripts with Fable (see here: https://axxes.com/en/net/compiling-f-scripts-with-fable-2-2/) as Just another metaprogrammer has mentioned, though personally it's not my preferred approach (I'm happy with .fs) and I'd argue that it's more akin to react / jsx since it's client side and uses react under the hood.

PHP scripts that combined with Python modules

My question may be incorrect or even strange, but I'm really interested in such programming experience, and there is two reasons for that:
As a PHP developer I should do my work so I can't just switch to other programming language that easy; however, there is a lot of things that causes a lot of pain to write in PHP.
As a Python beginner I'm already a huge fan of this language, and there are things that can be done a lot easier and, IMHO, in more righteous way that PHP implementation suggests.
For example, I've been writing a broadcasting multiple-connection socket server in PHP, and anybody who has done similar thing would understand how many restrictions will cause such solution - detecting disconnect if client just closed browser is dreadful. Looking at broadcasting server implementations in Python makes me feel more comfortable.
Also, a think about applications that could work, say, in offline mode to gather user input and sending it to the processing server later, or stand-alone applications that are connected to a website, etc.
Searching the web is poor in this case. All I've found is PiP, but it was released too long ago and not documented well - there is probably a good reason for that.
I would be glad to hear any thoughts about this, because I understand that this idea is kind of crazy and looks like not a lot of people is concerned about it.
Some time ago I ran into a similar dilemma. The solution I found was use xml-rpc to expose python objects and methods so I can use them from php scripts. Here I left you the documentation of both.
Python: Python xml-rpc.
PHP: XML-PHP
EDIT: Adding example. The examples are the same that in the documentation. I just changed them a bit to make them shorter. In client.php I only call the div function from python server. Add the others your self.
server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
requestHandler=RequestHandler)
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x,y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
def div(self, x, y):
return x // y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
client.php
<html>
<head><title>xmlrpc</title></head>
<body>
<h1>Php - Python - XMLRPC Demo</h1>
<?php
// Note that the path to xmlrpc.inc file is relative.
// to this file.
include("xmlrpc/lib/xmlrpc.inc");
// Params to python function 10 and 5.
// Build the message you want send.
// The message takes the function name and the params. See doc for details on how
// build params, is pretty easy.
$msg = new xmlrpcmsg( "div", array(new xmlrpcval(10, "int"), new xmlrpcval(5, "int")) );
// Build a XMLRCP - Client.
$client = new xmlrpc_client("/RPC2", "localhost", 8000);
// And send the message.
$response = $client->send($msg);
// From here all should look familier to you.
if(!$response->faultCode())
{
$v=$response->value();
echo "The result from div is" . htmlspecialchars($v->scalarval());
}
else
{
print "An error occurred: ";
print "Code: " . htmlspecialchars($r->faultCode())
. " Reason: '" . htmlspecialchars($r->faultString()) . "'</pre><br/>";
}
?>
<hr/>
</body>
</html>

Scala Lift - Run PHP file from within scala runtime

I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.

How to read GTFS protocol buffer in PHP?

I have a GTFS protocol buffer message (VehiclePosition.pb), and the corresponding protocol format (gtfs-realtime.proto), I would like to read the message in PHP alone (is that even possible?).
I looked at Google's python tutorial https://developers.google.com/protocol-buffers/docs/pythontutorial and encoding documentation https://developers.google.com/protocol-buffers/docs/encoding and https://github.com/maxious/ACTBus-ui/tree/master/lib/Protobuf-PHP, but I am having a really hard time conceptualizing what is going on. I think I understand that gtfs-realtime.php is a compiled instruction set of the encoding defined in gtfs-realtime.proto (please correct me if I am wrong), but I have no clue how to get it to decode VehiclePosition.pb. Also, what are the dependencies of gtfs-realtime.php (or the python equivalent for that matter)? Is there anything else I have to compile myself or anything that is not a simple php script if all I want to do is read VehiclePosition.pb?
Thanks.
edmonscommerce and Julian are on the right track.
However, I've gone down the same path and I've found that the PHP implementation of Protocol Buffers is cumbersome (especially in the case of NYCT's MTA feed).
Alternative Method (Command Line + JSON):
If you're comfortable with command line tools and JSON, I wrote a standalone tool that converts GTFS-realtime into simple JSON: https://github.com/harrytruong/gtfs_realtime_json
Just download (no install), and run: gtfs_realtime_json <feed_url>
Here's a sample JSON output.
To use this in PHP, just put gtfs_realtime_json in the same directory as your scripts, and run the following:
<?php
$json = exec('./gtfs_realtime_json "http://developer.mbta.com/lib/GTRTFS/Alerts/VehiclePositions.pb"');
$feed = json_decode($json, TRUE);
var_dump($feed);
You can use the official tool: https://developers.google.com/transit/gtfs-realtime/code-samples#php
It was released very recently. I've been using it for a few days and works like a charm.
I would assume something along the lines of this snippet:
<?php
require_once 'DrSlump\Protobuf.php';
use DrSlump\Protobuf;
$data = file_get_contents('data.pb');
$person = new Tutorial\Person($data);
echo $person->getName();
as taken from the man page: http://drslump.github.io/Protobuf-PHP/protobuf-php.3.html
Before that step, I think you need to generate your PHP classes using the CLI tool as described here: http://drslump.github.io/Protobuf-PHP/protoc-gen-php.1.html
so something along the lines of:
protoc-gen-php gtfs-realtime.proto
Sorry Harry Truong, I tried your executable but it returns always NULL.
What I am doing wrong?
Edit: The problem is that I have no permission to execute in my server. Thanks for your executable.

Access the webserver by using javascript instead of php

I'm now using phonegap to develop a application. I have found a similar php code which can assess to a local server here, but unfortunately phonegap doesn't support php.
Can anyone help me to 'translate' the php code below into JQuery ajax or any other javascript code? Thanks!
require_once('nusoap.php');
/* create client */
$endpoint = "http://www.pascalbotte.be/rcx-ws/rcx";
$ns = "http://phonedirlux.homeip.net/types";
$client = new soapclient($endpoint);
// queryRcx is the name of the method you want to consume
// RcxQuery_1 is the name of parameter object you have to send
// x and y are the names of the integers contained in the object
$result = $client->call('queryRcx',array('RcxQuery_1' => array('x' => 12,'y' => 13)), $ns);
print_r($result);
Step 1. Resolve the 404 associated with http://www.pascalbotte.be/rcx-ws-rpc/rcx?WSDL
Step 2. Get a JavaScript SOAP client.
Step 3. ... ... ...
Step 4. PROFIT!
Seriously though. All this really takes is a JavaScript based SOAP client. While they aren't a dime-a-dozen, they are pretty common. The one above is for jQuery, but it is easy enough to find other implementations.
The fact that the WSDL definition causes a 404 may or may not be a problem as the actual wsdl definition is technically optional, but you really want to figure out what happened.
You can add this header to the PHP file or .htaccess to avoid problems with cross domain reqs:
header('Access-Control-Allow-Origin: *');
Replace the all(*) with your domain ;)
Good luck!

Categories