Send variable from php to python - php

Here is my problem, I need to send a variable to a python script from php which isn't really that hard but I just found out that they are not on the same server. The php file is on server A and can be accessed at server-a.com and the python is on a different server that can be accessed at server-b.com.
This is my current code for the php and python which works when they are on the same server:
PHP:
// Call to the python script test.py with the JSON data
$result = shell_exec('python test.py ' . escapeshellarg(json_encode($data)));
// get data back from python, decode it and display it
$resultData = json_decode($result, true);
//var_dump($resultData);
echo $result;
?>
Python:
import sys, json
# Load the data that PHP testv2.php sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'status': 'Yes!'}
# Send it to PHP
print json.dumps(data)

Since you are on different servers you probably want to communicate via HTTP.
If your code is really THAT simple like shown in your example and will never become more complex, consider invoking Python via CGI.
For anything else (or if you simply prefer doing it properly) consider using WSGI and a framework such as Flask which allows you to define multiple endpoints using an url routing system.

Related

PHP Interfacing with Python -- Getting Null Return Value

I lifted some code off of StackOverflow to test some very basic PHP / Python integration, as I would like to eventually create a web interface for a Python machine learning platform I've been testing for a while now.
The code is as follows below:
PHP:
<?php
$data = array('1', '2', '3');
$result = shell_exec('python "C:\Program Files (x86)\Zend\Apache24\htdocs\Machine-Learning-Python-Integration\phptransfertest.py" ' . escapeshellarg(json_encode($data)));
$resultData = json_decode($result, true);
var_dump($resultData);
?>
Python:
import sys
import json
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
result = {'status': 'Yes!'}
print json.dumps(result)
But when I load this up in a browser, it only outputs NULL. I am unsure how to properly pass variables and files between Python and PHP, and most guides I have found tend to give me a NULL error.

Python request.post to php server

Different variants of this question litter google, but I am not finding a solution specific to my needs. I am trying to send a JSON string from a client running python to a web server that is using PHP. The JSON string contains the results from a select query.
I have found lots of examples and tutorials on how to generate the JSON in python and how to publish data from the server database to a user via the server's page.
What I am not finding is how to actually transfer the JSON from the Python script to the PHP script. I am using the Arduino YUN with Linino, and have tried a request.post() but get a "module not found" error.
A plain english explanation of how the data hand off should take place between the two devices would help greatly! Any suggestions on a good resource that actually shows an example of what I have described would be great too.
Python (Post):
#!/usr/bin/python
import requests
import json
url = 'http://xxx.xxx.x.xxx/reciever.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(payload), headers=headers)
PHP (Receiver):
<?php
print_r(json_decode($_POST['payload']));
?>
Maybe there is a totally different way that is better for posting a select query from a client to a server? Client will have dynamic IP's and the server will be web based.
Library requests isn't installed in Python by default. You need to get it first via pip or another package manager:
pip install requests
After that, you can use it.
There is also library, that is built in: urllib2. Example:
import urllib
import urllib2
url = 'http://xxx.xxx.x.xxx/reciever.php'
payload = {"device":"gabriel","data_type":"data","zone":1,"sample":4,"count":0,"time_stamp":"00:00"}
headers = {'content-type': 'application/json'}
data = urllib.urlencode(payload)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

Sending and receiving data to PHP from Python

I am working on a project that requires a python client to execute functions and send data to a PHP server. To clarify, the python program is on a client computer, the PHP script is hosted on a webserver (24hosting). I need the python script to be able to get data from an SQL server hosted on the same site as the PHP server. I have already written code to get the SQL table data using PHP, I just need a way to get that data into python.
I am hoping the process will look like this:
Data in SQL Table
Get data using PHP
Use python on remote computer to recieve data from PHP
Any advice on how to go about this will be greatly appreciated!
Take a look at the requests api library in Python. You can use this library to let your python client make web based calls to our php code hosted in a web-server.
You can pass data from PHP to Python via JSON like this.
PHP script myscript.php reads a database table into a PHP array which is then encoded as JSON:
$fields = array('pkey', 'name', 'occupation');
$result = $conn->query($sql);
$row_data = array();
while ($row = $result->fetch_assoc()) {
$row_data[] = $row;
}
$rowfields = array('cols' => $fields, 'rows' => $row_data);
$json_data = json_encode($rowfields);
echo $json_data;
Then on a local computer running python:
import json
import urllib2
url = r'http://www.mysite/myscript.php'
response = urllib2.urlopen(url)
remote_data = json.load(response)
In this example, remote_data is a python dictionary with our server data.
You probably want to send the data from the PHP webserver in some easy-to-parse format such as JSON. Python has good parsing libraries for JSON, and for sending/receiving HTTP requests. The later is not part of the standard library, but can be downloaded using pip or similar.

duplicate HTTP POST from python script with Lua

I have a python script which succesfully posts a file to my localhost webserver running apache in <100ms. Now, I want to do exactly the same with Lua. I have come up with a script that posts that same image to my webserver but it takes a whopping ~24s to complete. The php running on the server receives and stores the file properly but for the Python script, the file comes in the $_FILES array whereas for the Lua script, I have to copy content from the php://input stream - also, looking at both POST requests with wireshark, I can see a 7667 POST from the Python script but not from the Lua, instead only a few TCP SYN & ACK frames. Any idea why my Lua script is missing the actual POST (incl. url) but it still seems to work (but really slow):
Some code is below:
Python
#!/usr/bin/python
import urllib2
import time
from binascii import hexlify, unhexlify
import MultipartPostHandler
fname="test.gif"
host = "localhost"
#host = "semioslive.com"
URI="/test.php"
#URI="/api/gateway.php"
nodemac ="AABBCC"
timestamp = int(time.time())
func="post_img"
url = "http://{0}{1}?f={2}&nodemac={3}&time={4}".format(host, URI,func,nodemac,timestamp)
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
data = {"data":open(fname,"rb")}
#r.get_method = lambda: 'PUT'
now = time.time()
response = opener.open(url, data, 120)
retval = response.read()
if "SUCCESS" in retval:
print "SUCCESS"
else:
print "RESPONSE sent at "+retval
print " Now "+str(time.time())
print "Request took "+str(time.time()-now)+"s to return"
Lua
#! /usr/bin/lua
http = require("socket.http")
ltn12 = require("ltn12")
local request_body = ltn12.source.file(io.open("test.gif"))
local response_body = {}
http.request{
url = "`http://localohst/test.php`",
method = "POST",
headers = {
["Content-Type"] = "multipart/form-data",
["Content-Length"] = 7333
},
-- source = ltn12.source.file(io.open("test.gif")),
source = request_body,
sink = ltn12.sink.table(response_body)
}
print(response_body[1]) --response to request
PHP
<?
if (isset($_FILES['data']))
move_uploaded_file($_FILES['data']['tmp_name'],"post(python).gif");
else
copy("php://input","post(lua).gif");
echo "SUCCESS!";
?>
Make sure your Lua script is sending the same HTTP headers. The important part for PHP is that the form with attached file upload is sent as "multipart/form-data", and the file must be properly embedded in the POST body of the HTTP request as a multipart mime message.
I cannot see if your Lua script actually does this, but I think no. Otherwise PHP would be happy.

Python: how to make HTTP request internally/localhost

I want to send some parameters from a python script on my server to a php script on my server using HTTP. Suggestions?
This is pretty easy using urllib:
import urllib
myurl = 'http://localhost/script.php?var1=foo&var2=bar'
# GET is the default action
response = urllib.urlopen(myurl)
# Output from the GET assuming response code was 200
data = response.read()

Categories