Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 913
ishita Avatar asked Nov 26 '13 10:11

ishita


People also ask

How do you call a PHP function from Python?

To run a Python script from PHP, we can use the shell_exec function. $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; to call escapeshellcmd to escape the command string. Then we call shell_exec to run the $command .

Can Python run PHP?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

Can we use PHP with flask?

Flask is not compatible with php.

How do I open a php file in Python?

php $command = escapeshellcmd('python test.py'); $output = shell_exec($command); echo $output; ?> Save the above script with the . php extension. Start your webserver and visit your web server domain.


2 Answers

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)
like image 178
transilvlad Avatar answered Sep 27 '22 01:09

transilvlad


Small update to previous response:

For python3 code string should be encoded to bytes-like object

php(code.encode())
like image 40
Volo Avatar answered Sep 23 '22 01:09

Volo