O P
O P

Reputation: 2365

Pass multiple Python variables to PHP

HTML

This is a form that accepts a user's input (url):

<form method="post" action="/" accept-charset="utf-8">
    <input type="search" name="url" placeholder="Enter a url" />
    <button>Go</button>
</form>

PHP (Laravel)

This controller stores the value of the user's input (url) into a variable for use in the python script.

$url = Input::get('url');
$name = shell_exec('path/to/python ' . base_path() . '/test.py ' . $url);
return $name;

Python

The script passes what the user input and takes the text after a forward slash and displays it.

url = sys.argv[1]
name = url.split('/')[-1]
print(name)

Going back to the PHP, it returns the value of what was executed in the Python script. If a user inputs the url: http://example.com/file.png it will successfully return the string file.png

Everything about this works, but I'm realizing that I'm limiting myself, since the shell_exec command is only going to paste out the string that is returned from the python script. What do I need to do if I want to have multiple variables returned?

Python in question

url = sys.argv[1]
name = url.split('/')[-1]
test = "pass this text too!"
# ? what goes here ?

So the HTML page should now return file.png and pass this text too!

Am I going to need to return an array or json in the python and then extract the array/json in PHP?

NOTE: I am aware of security flaws/injections in these examples, these are stripped down versions of my actual code.

Upvotes: 0

Views: 5059

Answers (2)

Halayem Anis
Halayem Anis

Reputation: 7785

In this case, your Python script has to return a formatted response, that PHP script can parse properly and determine variables with their values
for example, your python code has to return something like that :

file_name=file.png;file_extension=png;creation_date=1/1/2015;

After that in your php code yo do the necessary stuff

$varValues = explode(";", $PythonResult);
foreach($varValues as $vv) {
    $temp = explode("=", $vv);
    print 'Parameter : ' . $temp[0] . ' value : ' . $temp[1] . '<br />';
}

Upvotes: 0

Andrew_Lvov
Andrew_Lvov

Reputation: 4668

You can return a an array, but be sure that elements don't contain the delimiter. Like print(','.join(name, test)). Or you can encode to json like json.dumps([name, test]), then parse json in PHP. Second one is better, of course.

Upvotes: 2

Related Questions