PHP scripts that combined with Python modules - php

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>

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.

sending message out of a sandbox to a custom application

I got an application which uses flash for it's interfaces, and I want to extract information from this application, and parse/use it in my own application (which processes the data, stores the essentials in a mysqldb and so on).
The .swf files are written in AS2 and can be modded quite easily.
So my goal is to send information (really just information. Being able to send numbers (of a at least decent size) would enable me to implement my own protocol of encoding and partitioning) by any means, I am certainly not picky about the means.
Here is my current approach (not my own idea, credits to koreanrandom.org. I merely use their source to learn):
use DokanLib to mount a virtual filesystem (and implement the getFileInformation-handler)
use LoadVars inside the AS2-Environment with parameters like "../.logger/#encoded_information"
since getFileInformation gets the accessed filename as a parameter, I can decode it, put several ones back together (if they had to be splitted, windows does not seem to like filenames with several hundred characters length) and use the decoded data
However, my application causes bluescreens quite often (dont ask why. i got no clue, the bluescreen messages are always different) and the devs at koreanrandom.org dont like being asked too many questions, so i came to ask here for other means to pass information from a sandboxed flash-environment to a prepared listener.
I started thinking about weird stuff (ok, abusing a virtual filesystem & filenames as a means of transport for information might be weird too - but it is still a great idea imo) like provoking certain windows-functions to be called and work with global hooks, but i didnt grasp a serious plan yet.
The "usual" methods like accessing webservers via methods like this dont appear to work:
var target_mc = createEmptyMovieClip("target_mc", this.getNextHighestDepth());
loadVariables("http://127.0.0.1/Tools/indata.php", "target_mc", "GET");
(indata.php would have created a file, if it was accessed, but it didnt.)
XMLSocket doesnt work either, i tried the following code sample (using netcat -l on port 12345):
Logger.add("begin");
var theSocket:XMLSocket = new XMLSocket();
theSocket.onConnect = function(myStatus) {
if (myStatus) {
Logger.add("XMLSocket sucessfully connected")
} else {
Logger.add("XMLSocket NO CONNECTION");
}
};
theSocket.connect("127.0.0.1", 12345);
var myXML:XML = new XML();
var mySend = myXML.createElement("thenode");
mySend.attributes.myData = "someData";
myXML.appendChild(mySend);
theSocket.send(myXML);
Logger.add("socket sent");
doesnt work at all either, the output of the logger was just begin and socket sent
Annotation: the logger was created by the guys from koreanrandom.org and relies on their dokan implementation, which never caused a bluescreen for me. cant spot my mistake in my implementation though, so i started to look for other means of solving my problem.
EDIT: what the hell is wrong with your "quality messages system"? appearently it didnt like me using the tags "escaping" and/or "information".
hmm, hard to say, try sendAndLoad instead of loadVariables
example:
var result_lv:LoadVars = new LoadVars();
var send_lv:LoadVars = new LoadVars();
send_lv.variable1=value1;
send_lv.variable2=value2;
f=this;//zachytka
result_lv.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
} else {
trace("error");
}
};
send_lv.sendAndLoad("http://127.0.0.1/Tools/indata.php", result_lv, "GET"); //you may also use POST
this should work. the reason it's not working may also be flash security settings. try either moving the stuff to a real server or open up the flash settings manager (there's an alternative online version too) and add the 127.0.0.1 to trusted domains and/or testing file location to the trusted locations (i use C:*)

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 could one use Node.js to run JS from PHP and return a value back?

This isn't for anything serious, more so to just play around and experiment. Just not sure where I would start. Also not bound to Node.js, just figured it's the most popular server-side JS tool around.
Though if there are some major technical reasons why one shouldn't do something like this on a real site, feel free to throw them out there.
What I'm asking about is something like…
$input = $js_string_built_via_php;
if ($run_on_server)
$output = node.js($input);
else
$output = '<script type="text/javascript">'.$input.'</script>';
echo $output;
There are several alternatives to using node here.
Have you seen the V8js PHP extension, which integrates the V8 engine with PHP? I don't have any experience with using it myself, though.
Alternatively, similar to using node, you could install Rhino (available in the Ubuntu repos, at least from 12.04). Or another command line javascript interpreter. Then you can execute javascript from the shell:
rhino -e '<javascript code>';
So you should be able to do something like the following. You would have to use print to output data and then parse the output back in php somehow:
<?php
function execute_js($script) {
return shell_exec('rhino -e '.escapeshellarg($script));
}
$javascript = "
function add(a,b) {
return a+b;
}
print(add(5,6));
";
$result = execute_js($javascript);
print $result;
I doubt this would be a good idea in a production application and seems like it might be quite vulnerable with a much greater attack surface. With clients being able to inject javascript code that actually gets executed on the server. It's probably very slow at load also.
A better solution 3 years later?
dnode-php would a better solution for what you want today.
There is a cool introduction here. As mentioned by the author Henri Bergius:
DNode is a remote method invocation protocol originally written for
Node.js, as the name probably tells. But as the protocol itself is
quite simple, just sending newline-terminated JSON packets over TCP
connections, implementations have started popping up in other
languages. You can talk DNode in Ruby, Perl, Python, Java, and now
PHP.

Communication, Passing Info between PHP App and Ruby App

I primarily work in PHP and prefer to do so since there seem to be more jobs in this language, at least in my area (and I'm still fairly new to it so I want to continue to learn the language better).. but for some things I want to do I need to use the WWW Mechanize library that doesn't work with PHP but does with Ruby (yes I know PHP has some alternatives but I have tried them and they don't work for me so I need to do this), so I'd like to write most of my app in PHP and then just call Ruby when I need to use this library, then pass the info back to PHP, yes I know this would be "slow" but thats not an issue in this case as this isn't a public web app, its just for business use..
I'm wondering what the best way would be to pass info between the 2 languages.. I have thought of using http POST (like with Curl in PHP) to do this but not sure if this is the most efficient way any.. any info is appreciated, thanks
There are two different ways that I would do this:
\1. In ruby, set up a non-HTTP server that only listens on '::' (or 127.0.0.1 if you don't like ipv6). Then, every time your PHP script needs to do something, it can connect to the server and pass data to it. This would be the fastest solution because the ruby script doesn't need to start up every time PHP needs to do something.
Example Ruby:
require 'mechanize'
require 'socket'
def do_mechanize_stuff(command, *args)
case command
when 'search_google'
# search google with args.join(' ')
when 'answer_questions_on_stackoverflow'
# answer questions on stackoverflow
# with mechanize
end
'the result to pass to PHP'
end
srv = TCPServer.new '::', 3000
loop do
Thread.new(srv.accept) do |sock|
sock.write(
do_mechanize_stuff *sock.gets.split(' ')
)
sock.close
end
end
Example Ruby client: (you will need to translate this to PHP)
require 'socket'
# This is a script that searches google
# and writes the results to stdout.
s = TCPSocket.new 'localhost', 3000
s.puts 'search_google how to use a keyboard'
until (r = s.gets).nil?
print r # a search result.
end
You could use process watching tools like http://god.rubyforge.org/ to keep the server running.
\2. Make the ruby script a command line utility, and use exec in PHP to call it.
An example command line script:
require 'mechanize'
def do_mechanize_stuff(command, *args)
# ... from previous example
end
do_mechanize_stuff ARGV.shift, ARGV
I would suggest following a Software as a Service Architectire (SOA) and running a Ruby/Rails application as a separate process. You'll have to develop an API between the two (a very simple one will work): using POST/GET as you first thought is a right way to go here.

Categories