Execute PHP Code in Python

Execute php code in Python

Example code:

import subprocess

# if the script don't need output.
subprocess.call("php /path/to/your/script.php")

# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()

Execute PHP script from python

require .. is relative to the current working directory/the PATH setting, not the current PHP file. When executing from Python, the working directory will be either undefined or simply different from what you might expect. Use an absolute import path/relative to the file:

require dirname(__DIR__) . '/functions/server_info.php';

Running a Python script from PHP

Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

In PHP use shell_exec function:

Execute command via shell and return the complete output as a string.

It returns the output from the executed command or NULL if an error
occurred or the command produces no output.

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

Into Python file test.py, verify this text in first line: (see shebang explain):

#!/usr/bin/env python

If you have several versions of Python installed, /usr/bin/env will
ensure the interpreter used is the first one on your environment's
$PATH. The alternative would be to hardcode something like
#!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate
what interpreter to use by having a #! at the start of the first line,
followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not
apply (but that "shebang line" does no harm, and will help if you ever
copy that script to a platform with a Unix base, such as Linux,
Mac, etc).

This applies when you run it in Unix by making it executable
(chmod +x myscript.py) and then running it directly: ./myscript.py,
rather than just python myscript.py

To make executable a file on unix-type platforms:

chmod +x myscript.py

Also Python file must have correct privileges (execution for user www-data / apache if PHP script runs in browser or curl)
and/or must be "executable". Also all commands into .py file must have correct privileges.

Taken from php manual:

Just a quick reminder for those trying to use shell_exec on a
unix-type platform and can't seem to get it to work. PHP executes as
the web user on the system (generally www for Apache), so you need to
make sure that the web user has rights to whatever files or
directories that you are trying to use in the shell_exec command.
Other wise, it won't appear to be doing anything.

call php function from python

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)

How can I call PHP script with arguments in python

The problem could be in the way you are passing arguments to subprocess.call

The function's signature is

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None)

From documentation:

args is required for all calls and should be a string, or a sequence
of program arguments. Providing a sequence of arguments is generally
preferred, as it allows the module to take care of any required
escaping and quoting of arguments (e.g. to permit spaces in file
names). If passing a single string, either shell must be True (see
below) or else the string must simply name the program to be executed
without specifying any arguments.

So your code should be something like this:

Output = subprocess.call(["bin/sudo", "-u", "username", "/bin/PHP", "pathtofilename.php", V1, V2])

Alternatively it could be

Output = subprocess.call(["bin/sudo -u username /bin/PHP pathtofilename.php " + V1 + " " + V2], shell=True)

but you should consider possible security issues.

Note: If you are on Python 3.5+ consider using subprocess.run, especially if you want to capture stdout or stderr with a CompletedProcess instance.

How do I run a php code string from Python?

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

Python: can't execute a php file

Thanks to @nitrin0 I found the answer:

if you want to use subprocess.run() you have to specify the FULL path of everything (Ex. subprocess.run(['/usr/bin/php', '/home/admin/hen-durance/writetofile.php ', word]))

if you want to use os.system() you can avoid to specify the path, but remember to format the command in a proper way (Ex. os.system('php writetofile.php ' + word) [notice the space before the closing quote, I didn't put that there before so my script executed php writetofile.phpword that obviously can't work])



Related Topics



Leave a reply



Submit