How to pass PHP variable values to Python via shell_exec - php

I have some variables defined in a PHP file. I then call a python script from the PHP with these variables as arguments. HOWEVER the values of the variables do not carry over to my python script, it seems as though they as passed as strings and not as variables:
$first = "doggy";
$second = "kitty";
$command = escapeshellcmd('python ./script.py $first $second');
$output = shell_exec($command);
The above code produces not "doggy" and "kitty" respectively in my Python script, but literally "$first" and "$second". I want doggy and kitty.
For example when I print in Python:
print sys.argv[1];
>>$first
is the output I am receiving.
My Python script is NOT outputting anything, the script interacts with an API that I wish to use these variables with.
I have tried these previous posts which seem to be near what I am asking. I am either not understanding them, or they are not working. Some answers are too technical or too vague.
Passing value from PHP script to Python script
PHP <-> Python variable exchange
If shell_exec is not the best way for this, I am open to new ideas. Any and all help is appreciated. Thanks for taking the time to look at my post.

A single quoted string will be displayed literally, while a double quoted string will interpret things like variables and new line sequences (\n).
Therefore, change from single to double quotes:
$command = escapeshellcmd("python ./script.py $first $second");
Read more about strings in the PHP manual: http://se1.php.net/manual/en/language.types.string.php

Related

How to run file in background by adding variable

Hey PHP developers I am newbie.
Today I want to run my process.php file in the background because it takes too much time to load... Here is the code that I want to use.
$proc=new BackgroundProcess();
$proc->setCmd('exec php <BASE_PATH>/process.php hello world');
$proc->start();
And I want to add this ids=$postid&reaction=$reaction variable instead of hello world.
And want to receive it with post in process.php file like this
$id =$_POST['ids'];
$type = $_POST['reaction'];
I am using this GitHub file
https://github.com/pandasanjay/php-script-background-processer/blob/master/README.md
Before doing downvote answer me I am a newbie in PHP.
You can try exec() for this. If you want to pass parameters then try like this.
//it will store logs to log_data.log
exec("php process.php $id $type >log_data.log &");
Hope this will work for you :)
Try like this
function execInBackground() {
//this will run in background
exec("php process.php $id $type > /dev/null &");
}
As soon as it is not HTTP request at all, you cannot access $_GET and $_POST superglobals. The right way to receive arguments in this case, is to access the array $argv. See official documentation:
http://php.net/manual/en/reserved.variables.argv.php
UPD: And, well, if you really want to pass $_GET/$_POST params to this script executed via shell, here is a dirty trick:
$get_params_as_string = base64_encode(json_encode($_GET));
$proc=new BackgroundProcess();
$proc->setCmd("exec php <BASE_PATH>/process.php {$get_params_as_string}");
$proc->start();
And in your process.php access it like this:
$get_params = json_decode(base64_decode($argv[1]), true);
So, we are just created JSON from $_GET array. Then, as we know that JSON string contains special characters(like ", {, }, etc), and to avoid dealing with problems of escaping and unescaping, we simply encode this string as base64. It guarantees us absence of special characters in result string. Now we can use this string as a single argument, which we will pass to shell command (your BackgroundProcess). And finally, in process.php we can access this string from $args[1], then decode from base64, then decode from JSON to a regular PHP array. Here we go.
This solution is provided only for educational purpose, please don't ever do it in real life.

how to decode the encoded array passed from php

I have problem in decoding the array passed from PHP. My PHP code is
$checkedJson = json_encode($dynamic_species);
$tmp = exec("/Python33/arr_pass.py $pressure $temp $checkedJson");
return $tmp;
If i print $checkedJson i get
{"species1":"CH4","species2":"C2H6"} as print statement
My python code is
species_list = sys.argv[3]
species_list_data = json.loads(species_list)
print(species_list_data['species1'])
This python script returns empty string as output to php
I am working for first time on JSON can anyone please help me.
Thanks in advance
This is neither a JSON nor Python question. What you want is to figure out how to get output back when your PHP program runs something via exec(). Basically you're lacking the output parameter; RTM at php.net. You should try:
exec("/Python33/arr_pass.py $pressure $temp $checkedJson", $output);
After which $output will be an array of lines that your exec'd script sent to its output. In your code, $tmp is assigned to the last line that the exec'd thing prints, so probably an empty line.
Plus you have one more challenge; the way you pass $checkdJson to the Python script will fail. You will have to quote it to make it one commandline parameter, so you'll probably need
exec("/Python33/arr_pass.py $pressure $temp '$checkedJson'", $output);
(note the extra single quotes).

Having trouble passing variable from php to bash

I'm trying to set up an html form that passes variables to a php script, that then passes them to a bash script.
I'm able to successfully pass variables from the html form to the php script, and I'm able to make the following pass variables to my bash script:
<?php
shell_exec('./bashscript.sh testarg1 testarg2 testarg3 testarg4');
?>
But, when I use the following:
<?php
shell_exec('./bashscript.sh $_POST[arg1] $_POST[arg2] $_POST[arg3] $_POST[arg4]');
?>
I end up with:
[arg1]
[arg2]
[arg3]
[arg4]
This is the first time I've tried passing from php to bash. The bracketed arguments post to a db with no prob. How would I change this to successfully pass the arguments to my bash script? thx.
Variables are expanded inside double-quoted string, not inside single-quoted strings.
shell_exec("./bashscript.sh $_POST[arg1] $_POST[arg2] $_POST[arg3] $_POST[arg4]");
This is basic PHP syntax, having nothing to do with using the shell.
You should also use escape_shell_arg to escape each argument before substituting it, in case it contains shell metacharacters.

php `exec` calls python script. how return strings from python?

I use exec function calling python script from PHP script. Python writes to standard output two strings which I need in PHP script. The problem is that in these strings could be end of line characters \n ( so formally there are many lines in output), and according to exec manual array $output will contain
each line in it. What is elegant way to escape \n characters so that $output will contain only two string I want and no post processing of these two string needed?
EDIT: I can change python script.
Print the output in an easily parsable format, such as JSON, and parse it from PHP. For example, instead of:
print foo
print bar
Use something like:
import json
print json.dumps([foo, bar])
You read the JSON output form PHP and decode it using json_decode($output) into the desired array.
There really is nothing you can do about this outside of changing the way the python script outputs.
It is really easy to clean the returned data though.
exec('yourcommand', $array);
array_walk($array, function($value, $key) {
return trim($value);
});

PHP string contains $ and incorrectly recognizes variable

Basically I'm sending a formatted string to a PHP script via POST
So say I have the string... "abcdef$ghikl" it will recognize $ghikl as a variable...
Is there any ways to tell PHP that no variables exist within this string?
I know how to hard code it, you just use "'", but since the string is being sent to the script, I don't know what to do...
Thanks guys
For the scope of the question, all the code that's really needed is this:
$string = $_POST['string'];
// a couple strcmp's here, just to see if the string == ""
$array = explode("+", $string);
Try escaping the $
"abcdef\$ghikl"
PHP won't see that as a variable unless you eval() it. Can you show us your code?

Categories