Sending and receiving data to PHP from Python - php

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.

Related

Display JSON data from POST request in PHP

I have an apache2 server and php file to receive json via POST in my php code like this
$json = json_decode(file_get_contents('php://input'), true);
$mac_ = $json["code"];
$userId_ = $json["msg"];
and saving it to mysql. This work when I send post via python's requests but not when I'm recieving data from API android device. - When I look at the apache log file, there is a connection, so I'm assuming that some data are received, but because I can't touch that API android device I'm not sure if this part $json["code"] has a right parameter. I would like to know a way to save somewhere all recieved data from this part
$json = json_decode(file_get_contents('php://input'), true);
because I can't check it by echo or so

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()

How to send xml file for asp.net webservice using php soap

I have to send a XML file to asp.net based webservice. I am using php soap client.
Here is the code:
$request = file_get_contents('myfile.xml');
$result = $soap->__doRequest($request, 'LOCATION_URL', 'ACTION_URL', SOAP_1_2);
AND the xml file looks like:
<ns1:header xmlns:ns1="http://something.com">
<ns1:timestamp>2014-01-01T13:20:00.000-05:00</ns1:timestamp>
But, every time its return a blank response. I didn't get any clue from any side.
Any help will be welcome.

Send variable from php to python

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.

How can I sending json data using Spring RestTemplate to PHP server

I am developing an android application and i using spring RestTemplate to get data from and post data to a PHP server. I tried to post data to PHP server, but PHP server got nothing. How can I post json data using Spring RestTemplate to PHP server and get the json from PHP server?
I solved the problem by myself. I add FormHttpMessageConverter to RestTemplate like this:
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new FormHttpMessageConverter());
And then I can post json data to PHP server. I got the json data in PHP server using:
$jsonData = $_POST['json'];
I fixed with
MultiValueMap<String, ArrayList<persona>> parts = new LinkedMultiValueMap<>();
parts.add("json", aaper);
restTemplate.postForLocation(url,parts);

Categories