How do I run a php code string from Python? - php

I've found that you can run a php file from Python by using this:
import subprocess
proc = subprocess.Popen('php.exe input.php', shell=True, stdout=subprocess.PIPE)
response = proc.stdout.read().decode("utf-8")
print(response)
But is there a way to run php code from a string, not from a file? For example:
<?php
$a = ['a', 'b', 'c'][0];
echo($a);
?>

[EDIT]
Use php -r "code" with subprocess.Popen:
def php(code):
p = subprocess.Popen(["php", "-r", code],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.communicate() #returns a tuple (stdoutdata, stderrdata)
if out[1] != b'': raise Exception(out[1].decode('UTF-8'))
return out[0].decode('UTF-8')
code = """ \
$a = ['a', 'b', 'c'][2]; \
echo($a);"""
print(php(code))
[Original Answer]
I found a simple class that allows you to do that.
The code is self-explanatory. The class contains 3 methods:
get_raw(self, code): Given a code block, invoke the code and return the raw result as a string
get(self, code): Given a code block that emits json, invoke the code and interpret the result as a Python value.
get_one(self, code): Given a code block that emits multiple json values (one per line), yield the next value.
The example you wrote would look like this:
php = PHP()
code = """ \
$a = ['a', 'b', 'c'][0]; \
echo($a);"""
print (php.get_raw(code))
You can also add a prefix and postfix to the code with PHP(prefix="",postfix"")
PS.: I modified the original class because popen2 is deprecated. I also made the code compatible with Python 3. You can get it here :
import json
import subprocess
class PHP:
"""This class provides a stupid simple interface to PHP code."""
def __init__(self, prefix="", postfix=""):
"""prefix = optional prefix for all code (usually require statements)
postfix = optional postfix for all code
Semicolons are not added automatically, so you'll need to make sure to put them in!"""
self.prefix = prefix
self.postfix = postfix
def __submit(self, code):
code = self.prefix + code + self.postfix
p = subprocess.Popen(["php","-r",code], shell=True,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
return child_stdout
def get_raw(self, code):
"""Given a code block, invoke the code and return the raw result as a string."""
out = self.__submit(code)
return out.read()
def get(self, code):
"""Given a code block that emits json, invoke the code and interpret the result as a Python value."""
out = self.__submit(code)
return json.loads(out.read())
def get_one(self, code):
"""Given a code block that emits multiple json values (one per line), yield the next value."""
out = self.__submit(code)
for line in out:
line = line.strip()
if line:
yield json.loads(line)

Based on Victor Val's answer, here is my own compact version.
import subprocess
def run(code):
p = subprocess.Popen(['php','-r',code], stdout=subprocess.PIPE)
return p.stdout.read().decode('utf-8')
code = """ \
$a = ['a', 'b', 'c'][0]; \
echo($a);"""
print(run(code))

Related

Shell_exec returns NULL in PHP

I am working on this project that requires me to upload pictures on PHP, execute the picture on python, fetch the output from python and display it again on PHP.
PHP code:
<?php
$command = shell_exec("python C:/path/to/python/KNNColor.py");
$jadi = json_decode($command);
var_dump($jadi);
?>
Python code:
from PIL import Image
import os
import glob
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import io, color
from scipy.stats import skew
#data train untuk warna
Feat_Mom_M = np.load('FeatM_M.npy')
Feat_Mom_I = np.load('FeatM_I.npy')
Malay_Col_Train = Feat_Mom_M
Indo_Col_Train = Feat_Mom_I
#Data warna
All_Train_Col = np.concatenate((Malay_Col_Train, Indo_Col_Train))
Y_Indo_Col = [0] * len(Indo_Col_Train)
Y_Malay_Col = [1] * len(Malay_Col_Train)
Y_Col_Train = np.concatenate((Y_Malay_Col, Y_Indo_Col))
Train_Col = list(zip(All_Train_Col, Y_Col_Train))
from collections import Counter
from math import sqrt
import warnings
#Fungsi KNN
def k_nearest_neighbors(data, predict, k):
if len(data) >= k:
warnings.warn('K is set to a value less than total voting groups!')
distances = []
for group in data:
for features in data[group]:
euclidean_dist = np.sqrt(np.sum((np.array(features) - np.array(predict))**2 ))
distances.append([euclidean_dist, group])
votes = [i[1] for i in sorted(distances)[:k]]
vote_result = Counter(votes).most_common(1)[0][0]
return vote_result
image_list = []
image_list_pixel = []
image_list_lab = []
L = []
A = []
B = []
for filename in glob.glob('C:/path/to/pic/uploaded/batik.jpg'):
im=Image.open(filename)
image_list.append(im)
im_pix = np.array(im)
image_list_pixel.append(im_pix)
#ubah RGB ke LAB
im_lab = color.rgb2lab(im_pix)
#Pisah channel L,A,B
l_channel, a_channel, b_channel = cv2.split(im_lab)
L.append(l_channel)
A.append(a_channel)
B.append(b_channel)
image_list_lab.append(im_lab)
<The rest is processing these arrays into color moment vector, it's too long, so I'm skipping it to the ending>
Feat_Mom = np.array(Color_Moment)
Train_Set_Col = {0:[], 1:[]}
for i in Train_Col:
Train_Set_Col[i[-1]].append(i[:-1])
new_feat_col = Feat_Mom
hasilcol = k_nearest_neighbors(Train_Set_Col, new_feat_col, 9)
import json
if hasilcol == 0:
#print("Indonesia")
print (json.dumps('Indonesia'));
else:
#print("Malaysia")
print (json.dumps('Malaysia'));
So as you can see, There is only one print command. Shell_exec is supposed to return the string of the print command from python. But what I get on the "var_dump" is NULL, and if I echo $jadi, there's also nothing. Be it using print or the print(json) command
The fun thing is, when I try to display a string from this python file that only consists 1 line of code.
Python dummy file:
print("Hello")
The "Hello" string, shows up just fine on my PHP. So, is shell_exec unable to read many codes? or is there anything else that I'm doing wrong?
I finally found the reason behind this. In my python script there are these commands :
Feat_Mom_M = np.load('FeatM_M.npy')
Feat_Mom_I = np.load('FeatM_I.npy')
They load the numpy arrays that I have stored from the training process in KNN and I need to use them again as the references for my image classifying process in python. I separated them because I was afraid if my PHP page would take too long to load. It'd need to process all the training data, before finally classifying the uploaded image.
But then when I execute my python file from PHP, I guess it returns an error after parsing those 2 load commands. I experimented putting the print command below them, and it stopped showing on PHP. Since it's all like this now, there's no other way than taking the worst option, even if it'd cost me long loading time.
I tested this in the console:
php > var_dump(json_decode("Indonesia"))
php > ;
php shell code:1:
NULL
php > var_dump(json_decode('{"Indonesia"}'))
php > ;
php shell code:1:
NULL
php > var_dump(json_decode('{"Indonesia":1}'))
php > ;
php shell code:1:
class stdClass#1 (1) {
public $Indonesia =>
int(1)
}
php > var_dump(json_decode('["Indonesia"]'))
php shell code:1:
array(1) {
[0] =>
string(9) "Indonesia"
}
you have to have it wrapped in {} or [] and it will be read into an object or an array.
After an error you can run this json_last_error() http://php.net/manual/en/function.json-last-error.php and it will give you an error code the one your's returns should be JSON_ERROR_SYNTAX

Rscript not found in mac

If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".
submit.php:
<?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output = exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>
1.R:
setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.
Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.
<?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);
Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)

Send json data to php api through python

I am new to python. I have created a gui based app to insert values into database.
I have created a Rest api to handle db operations. How can i append the api URL with json created in python.
app.py
from Tkinter import *
import tkMessageBox
import json
import requests
from urllib import urlopen
top = Tk()
L1 = Label(top, text="Title")
L1.pack( side = TOP)
E1 = Entry(top, bd =5)
E1.pack(side = TOP)
L2 = Label(top, text="Author")
L2.pack( side = TOP)
E2 = Entry(top, bd =5)
E2.pack(side = TOP)
L3 = Label(top, text="Body")
L3.pack( side = TOP)
E3 = Entry(top, bd =5)
E3.pack(side = TOP)
input = E2.get();
def callfunc():
data = {"author": E2.get(),
"body" : E3.get(),
"title" : E1.get()}
data_json = json.dumps(data)
# r = requests.get('http://localhost/spritle/api.php?action=get_uses')
#url = "http://localhost/spritle/api.php?action=insert_list&data_json="
#
url = urlopen("http://localhost/spritle/api.php?action=insert_list&data_json="%data_json).read()
tkMessageBox.showinfo("Result",data_json)
SubmitButton = Button(text="Submit", fg="White", bg="#0094FF",
font=("Grobold", 10), command = callfunc)
SubmitButton.pack()
top.mainloop()
Error:
TypeError: not all arguments converted during string formatting
i AM GETTING error while appending url with data_json ?
There is an error on string formating:
Swap this:
"http://localhost/spritle/api.php?action=insert_list&data_json="%data_json
by this:
"http://localhost/spritle/api.php?action=insert_list&data_json=" + data_json
or:
"http://localhost/spritle/api.php?action=insert_list&data_json={}".format(data_json)
The following statements are equivalents:
"Python with " + "PHP"
"Python with %s" % "PHP"
"Python with {}".format("PHP")
"Python with {lang}".format(lang="PHP")
Also, I don't think sending JSON data like this via URL is a good idea. You should encode the data at least.
You are trying to use % operator to format the string, and you need to put the %s placeholder into the string:
"http://localhost/spritle/api.php?action=insert_list&data_json=%s" % data_json
Or use other methods suggested in another answer.
Regarding the data transfer - you definitely need to use POST request and not GET.
Check this, using urllib2 and this, using requests.

Passing variables from php to python and python to php

I am breaking my head to make this work but I am in a dead end. I have no idea what I am doing wrong.
I play with php and python; trying to execute a python script through php exec(), return an output and pass it to another python script.
This is my workflow:
1) Through jquery and an ajax request I pass some data to a php file (exec1.php) which looks like this:
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module1.py $number $shape";
exec($command,$out,$ret);
print_r($out);
print_r($r); //return nicely 1.
2) The python file which I run Module1.py looks like this:
# this is a list of list of tuples
cls000 = [[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]]
# RETURN DATA TO PHP
print cls000
3) Then I have a nested AJAX request inside the success function of my previous AJAX request in which I pass the response (in this case the cls000 list) into a php script called (exec2.php) like this:
# PASS VARIABLES FROM FORM
$number = $_POST['numberOfClusters'];
$shape = $_POST['shapeFilePath'];
$clusterCoords = $_POST['response']; # response from previous Ajax request
// EXECUTE THE PYTHON SCRIPT
$command = "python ./python/Module2.py $number $shape $clusterCoords";
exec($command,$out,$ret);
print_r($out); ## THIS GIVES ME AN EMPTY ARRAY!!
print_r($ret); ## THIS GIVES ME A RETURN STATUS: 2
4) My Module2.py script looks like this:
number = int(sys.argv[1])
shape = sys.argv[2]
cls000 = json.loads(sys.argv[3])
# RETURN DATA TO PHP
print cls000
What am I doing wrong? If I remove this line 'cls000 = json.loads(sys.argv[9])' and return for example 'shape' everything works fine. But when I try to return cls000 I get a status code 2.
What am I missing here?

call php function from python

My PHP code:
function start($height, $width) {
# do stuff
return $image;
}
Here my Python code:
import subprocess
def php(script_path):
p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
result = p.communicate()[0]
return result
page_html = "test entry"
output = php("file.php")
print page_html + output
imageUrl = start(h,w)
In Python I want to use that PHP start function. I don't know how to access start function from Python. Can anyone help me on this?
This is how I do it. It works like a charm.
# shell execute PHP
def php(code):
# open process
p = Popen(['php'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, close_fds=True)
# read output
o = p.communicate(code)[0]
# kill process
try:
os.kill(p.pid, signal.SIGTERM)
except:
pass
# return
return o
To execute a particular file do this:
width = 100
height = 100
code = """<?php
include('/path/to/file.php');
echo start(""" + width + """, """ + height + """);
?>
"""
res = php(code)
Note that for Python3 you need res = php(code.encode()), see the answer below
Small update to previous response:
For python3 code string should be encoded to bytes-like object
php(code.encode())

Categories