Is there a way for PHP to pass HTML form variables (POST) directly to a python script called with "passthru" in PHP without PHP having to know the variable names?
Can PHP pass the HTTP POST request to python so that i.e. the cgi module in python will read it like it was passed "from the web"?
Basic setup: Joomla CMS, with the jumi module.
NB! Python 2.4, PHP 5.3.3 on RedHat 5.9 - only standard packages.
One of the jumi applications is a python script which creates a form, and also handles the POST variables.
Reason: A lot more python knowledge in our shop, and the python script does a lot in the background.
In the jumi PHP script I have:
<?php
$var1 = $_REQUEST['myVar1'];
$var2 = $_REQUEST['myVar2'];
echo passthru('/usr/bin/python /var/www/html/joomla/jumi/portal-ldap.py '.$myVar1.' '.$myVar2);
?>
The python scripts then uses sys.arvg to process these variables.
It works - by all means, but it also means that any additinal variables must be known to both scripts.
Is there a way for PHP to pass the form variables directly to the python script in a way so that the "cgi" module in Python can process the variables as it would if I ran the python script with a framework/cgi/mod_python/...?
Python handling form variables:
import cgi
form = cgi.FieldStorage()
var1 = form.getvalue("myVar1", "nothing")
var2 = form.getvalue("myVar2", "nothing")
If you absolutely want to read the values through cgi.FieldStorage, you could run the python script on an HTTP server, preferably limiting its access to localhost. Executing the call over HTTP would also be a lot more secure than passing the parameters to passthrough() unparsed.
Alternatively, you could change your python script to use the getopt module, which makes it easier to define the argument in key-value pairs like this (paths omitted for brevity):
python portal-ldap.py --myvar1 nothing --myvar2 nothing
If you decide to keep using passthgough(), do remember to escape all the arguments with escapeshellarg().
Edit: You could also json_encode($_REQUEST) and pass it as a parameter, then json.loads() it in Python to get the array as a dictionary.
I'll answer my own question to explain how I used the info I've gotten.
I must also add that I'm limited by using python 2.4 and (maybe not limited by) simplejson - since I'm on RedHat 5.9 in this project - and want/need to keep to the supplied packages. So I have web --> Joomla --> jumi --> php --> python --> backend...
Building on the answer and comments from Kaivosukeltaja and supporting articles executing Python script in PHP and exchanging data between the two and http://pymotw.com/2/json/
In the jumi application / php-script I have put (amongst other things) the following to allow HTTP POST to be sent as a JSON object to my supporting python script.
echo passthru('/usr/bin/python /var/www/html/joomla/jumi/ldap-script.py '. escapeshellarg(json_encode($_POST)))
Then, in the python script I use sys.argv to read the variable, and simplejson to map the json object from PHP to a python dictionary (heavily simplified):
import sys
import simplejson as json
myjson = sys.argv[1]
mydict = json.loads(myjson)
I can now test if my desired keys can be found:
if ( 'var1' in mydict):
print mydict['var1']
The user posts to these variables in a simple form:
<form name="INPUT" action="" method="POST">
MyVar1 <input type="number" name="var1">
<input type=SUBMIT" value="Submit">
</form>
The avid reader will see that "var1" is referenced in most of these steps, while PHP isn't, don't have to be, aware of it.
Related
I'm trying to execute a piece of php code with the php command in the ubuntu terminal. I'm testing it with a sample code that you can find here.
I created a file with the code, calling it welcome.php, and tried executing it with:
php welcome.php
And obviously says there are undefined indexes, because it expects arguments via POST
Obviously I would like to do is to run it with the POST arguments as well. I tried the following:
declare -A _POST
_POST[name]="Sample name"
_POST[email]="sample#mail.com"
Before executing again, but the result still doesn't show. So is there any way I can declare the POST arguments manually in order to achieve loading the html file properly?
----------------- Context, in case it seems relevant -----------------
I'm programming a modest C server for my studies, and among the functionality required, there is executing php scripts. So my idea is to execute whatever command is required and generate the html output in a file that is later read and transmitted. Parsing the arguments as keys and values is not a problem (although yet to be done).
So far I know, you need to create a post request to a server to get the $_POST variable's values. In case you want to generate an HTML file, you can pass values through the argument, process it and return (print) an HTML document.
I want to execute python script with post data and get result from there using curl in php. If anyone have done this kind of functionality then please help. I have searched a lot but didn't get anything.
This is my python script path
cgi-bin/interactive.py
And i want to pass title=abc as post data.
I have done it with shell_exec in php file,
$command = escapeshellcmd('cgi-bin/interactive.py test');
$output = shell_exec($command);
echo $output;
But in this i am facing issue with sys.argv to fetch argument in python file.
Is it possible to pass argument with key=value with shell_exec? If yes then it can solve my problem otherwise i need to call with curl post data.
Thanks in advance!
To do advanced parsing of shell arguments you can use getopt or argparse modules. They are highly configurable and flexible.
Passing post data via shell arguments is, however, not proper as per the CGI spec (if this is supposed to be a true CGI application). Post data comes from stdin in CGI, so in your Python program you can read in the HTTP response like regular user input, and then parse out the POST data. See this thread for more info.
On this server, I can use both .cfm and .php files. Both types will be parsed, as expected.
However, I want .cfm files to be parsed for php, as well. For example,
//test.cfm:
<cfoutput>hello from cf</cfoutput>
<?php echo 'hello from php'; ?>
// outputs the php, verbatim, without processing :(
I know that I can change the php config, to parse .cfm. I dont know what order the parsing will take place or any other pros and cons, tricks and tips.
The goal here is that I want to wrap php (which i know well) into a cfm file (much less experience). The cfm file will be in an admin section, which automatically checks the user auth, and includes other cf files.
So, it seems to me that if coldfusion parses the file (checking the user-auth and all that), then hands it over to php, that would be the process that I am looking for.
This has been done:
See: http://www.barneyb.com/barneyblog/projects/cfgroovy2/
Most of the documentation has mixing ColdFusion and Groovy, but other languages can be mixed in too.
Example code:
<cfimport prefix="g" taglib="engine" />
...
<h2>Run some PHP (via Quercus)</h2>
<cftry>
<g:script lang="php">
<?php
$variables["myArray"][] = "Pretty Happy People wrote PHP.";
echo "<pre>";
var_dump($variables["myArray"]);
echo "</pre>";
?>
</g:script>
<cfcatch type="CFGroovy.UnknownLanguageException">
<p>Quercus needs to be added to your classpath for the PHP example to work</p>
</cfcatch>
<cfcatch type="any">
<p>Error running PHP code: #cfcatch.message#</p>
<p>#cfcatch.detail#</p>
</cfcatch>
</cftry>
Source: https://ssl.barneyb.com/svn/barneyb/cfgroovy2/trunk/demo/index.cfm
It will depend on the ColdFusion Application Server, what it supports and what level of interoperability you want. Generally if you want to be able to mix variables across statements, then you need to share the ColdFusion pageContext and make sure that php variables are written and updated. I don't believe that the example above does this, but I am happy to stand corrected. The other alternative is to called ColdFusion from PHP, again using Quercus. These 2 articles will help you do this. The first shows how to call Java from PHP, the second how to call ColdFusion from Java.
http://quercus.caucho.com/quercus-3.1/doc/quercus.xtp#Instantiatingobjectsbyclassname
http://help.adobe.com/en_US/ColdFusion/10.0/Developing/WSe61e35da8d318518-106e125d1353e804331-7ffb.html
Firstly create a ColdFusion component that can render ColdFusion dynamically
<cfcomponent displayname="ColdFusion renderer" output="false">
<cffunction name="render" returntype="'String' or 'Any'">
<!---
Do something with the coldfusion code here e.g:
write to a file using <CFFILE> and then <CFMODULE> or <CFINCLUDE>,<CFSAVECONTENT> it
or if the ColdFusion is all script, use the evaluate() function
--->
</cffunction>
</cfcomponent>
the invoke the component in PHP, via Java, using the CFCProxy
<?php
function cfml($code)
{
$cfc = new Java("coldfusion.cfc.CFCProxy", "path/to/cfc/above");
$cfc.render($code);
}
echo 'hello from php';
cfml(<<<EOT
<cfoutput>Hello from CF</cfoutput>
EOT
);
?>
At the moment I am planning a project with the RaspberryPi.
Therefore I plan to write a script in Python that runs in the background and reacts to user input (buttons, rotary knob, etc.).
Additional to the Python script I have a webinterface with PHP under it. The goal is to lat the user change settings through the webinterface and pass the changed variables (e.g. a Twitter username) to the Python script so it can update its variables.
Unfortunatelly I have no idea how to pass data to the running Python script. Do you have any ideas?
store modifiable settigns in a json file
settings.json
{"twitter_user": "bob"}
before doing something load your json settings
myscript.py
import json
def do_something():
settings = json.load(open("settings.json"))
print settings["twitter_user"]
update your settings.json via php as needed
myscript.php
function change_twitter_user($uname){
$settings = json_decode(file_get_contents($file));
$settings["twitter_user"] = $uname
file_put_contents("/path/to/settings.json",json_encode($settings ));
}
thats probably the easiest way to do it
(although you do know that python has some very nice web stuff also right?)
I'm developing a little web server in C++, now I'm trying to implement PHP support for my WS, or better I'm trying to figure out how to implement that.
But I've got some doubts: for now I have the client's request in a std::string, if it's a static request there's no problem: let's find file and put in on socket buffer; if it's a dynamic request(PHP only for now), of course I will need to call the interpreter(std::system() ??).
Now my mainly doubt is about forms, I get my POST request and I save form fields in a string, but now: How can I fill $_POST used in my php script and call the interpreter? I could put my fields string as argv by "php -f file.php "fields string" but ,of course, it's awful.
To pass the POST body, you basically pipe it in
echo "$POST_BODY" | php-cgi
For C and C++ you don't want to use just popen(), but also capture the output and stderr. So you need something like: how to control popen stdin, stdout, stderr redirection?