I am getting strings through an HTML form and storing them in PHP varibles using:
$var1=$_GET['name']
Now I pass these strings to a python script using
shell_exec("python_file.py $var1")
Suppose, string received in PHP is something likehello world. when the variable is passes to the python file. Python thinks of it as 2 different arguments like :
##python code
arg=sys.argv
print arg[0] -> python_file.py
print arg[1] -> 'hello'
print arg[2] -> 'world'
what is a workaround for this ?
I tried passing the sting into additional quotes. But it does not help.
I have not added any split() function in the python code.
EDIT: The variable are entries in the database. The python script opens the database and the variable defines the corresponding changes. So if the python file reads one variable as 2 due to whitespace. It adds incorrect entries in incorrect columns in the database
Usually you might want to use quotes:
shell_exec('python_file.py "'.$var1.'"') - last quote is the simple quote
You can also use escapeshellarg() which will adequately prepare the argument for the shell, doing what I said, and more so that even quotes are properly passed in arguments.
It is the recommended solution for passing arguments from user input and will avoid disasters such as escape-shell vulnerabilities.
What I tried:
test.py:
import sys
print(sys.argv)
exec.php:
<?php $arg = "hello world";
print(shell_exec('python3 test.py '.escapeshellarg($arg))); ?>
In my shell:
$php5 exec.php
['test.py', 'hello world']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With