Running Python Script with PHP Variables

I am writing a simple application that uses information from a form, passes it through $ _POST to a PHP script that runs a python script and prints the results. The problem I ran into is that my python script is actually not working with passed arguments.

process3.php file:

<?php $start_word = $_POST['start']; $end_word = $_POST['end']; echo "Start word: ". $start_word . "<br />"; echo "End word: ". $end_word . "<br />"; echo "Results from wordgame.py..."; echo "</br>"; $output = passthru('python wordgame2.py $start_word $end_word'); echo $output; ?> 

Output:

 Start word: dog End word: cat Results from wordgame.py... Number of arguments: 1 arguments. Argument List: ['wordgame2.py'] 

At the top of my wordgame2.py, I have the following (for debugging purposes):

 #!/usr/bin/env python import sys print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) 

Why is the number of arguments passed is not 3? (Yes, my form submits data correctly.)

Any help is much appreciated!

Edit: I can add that it starts when I directly say this start and end word ... something like this:

 $output = passthru('python wordgame2.py cat dog'); echo $output 
+7
variables python php forms
source share
2 answers

Update -

Now that I know PHP, the mistake is to use single quotes ' . In PHP, single quotes are considered literals; PHP does not evaluate the contents inside it. However, double-quoted strings are evaluated and will work as you expect. This summarizes nicely in this SO answer . In our case

 $output = passthru("python wordgame2.py $start_word $end_word"); 

will work, but the following will not -

 $output = passthru('python wordgame2.py $start_word $end_word'); 

Original answer -

I think the error lies in

 $output = passthru("python wordgame2.py $start_word $end_word"); 

try it

 $output = passthru("python wordgame2.py ".$start_word." ".$end_word); 
+9
source share

Thanks for your contributions. I figured out my problem with this simple fix:

 $command = 'python wordgame2.py ' . $start_word . ' ' . $end_word; $output = passthru($command); 

For passthru to correctly process PHP variables, it must be concatenated before execution.

+1
source share

All Articles