I'm trying to execute a py file from php.
here is my code:
//usage python my.py var1 var2
$libre = 'python ../../../../root/py/my.py '.$var1.' '.$var2.'';
$cleanlibre = escapeshellarg($libre);
echo exec($cleanlibre);
What is wrong?
Why is it returning nothing?
I also need to know how to secure exec well. Thanks.
--edit--
Used passthru
$libre = 'python ../../../../root/py/mech.py '.$var1.' '.$var2.'';
$cleanlibre = escapeshellarg($libre);
passthru($cleanlibre, $result);
echo $result;
//returned 127 <- i don't know where thats from.
escapeshellarg shall only be used to escape the arguments, not the whole command.
//usage python my.py var1 var2
$libre = 'python ../../../../root/py/my.py '.escapeshellarg($var1).' '.escapeshellarg($var2).'';
echo exec($libre );
exec return result in second argument of function, see http://php.net/manual/en/function.exec.php
Related
I have following JAVA program which has been converted to JAR file and placed in the same directory as my PHP file.
So basically it takes an argument passed by PHP and displays it
public class Test {
public static void main(String[] args) throws Exception {
//Takes the value passed from the PHP
String Name = (new String(args[0])).toString();
//This will be treated as Output Parameter which will be returned to PHP
System.out.println("Return to PHP");
}
}
Below is my PHP code which will execute the JAR file and pass the required 1 parameter to the JAR.
<?php
$arg1 = "My_INPUT_PARAMETER";
shell_exec("java -jar TEST.jar $arg1");
echo "Done";
?>
I read somewhere that what ever the placed in Sysout (System.out.println) will be treated as output parameter or Return value to PHP.
So in my case it will be String "Return to PHP".
But I am not able to get the value to PHP and display it.
I tried placing a output value in the exec statement but its not working.
I tried below code but its throwing me error.
<?php
$arg1 = "My_INPUT_PARAMETER";
$output = '';
shell_exec("java -jar TEST.jar $arg1", $output);
echo "Done";
echo $output;
?>
Can anyone help me out here, How can I get a return value from PHP or output parameter from PHP and display it or use it in my PHP and continue with other execution part.
Thanks #Roland Starke.
So basically we can use 2 statements to run the JAR file from PHP:
EXEC and SHELL_EXEC.
EXEC will hold all the return values from JAR file and we can use it as Array and Display the required output parameter.
SHELL_EXEC will hold all the output parameters and it will display all at once.
<?php
$arg1 = "Multi Return";
exec("java -jar TEST.jar $arg1",$output);
echo $output[0]."<br/>";
echo $output[1];
echo "-------------------------------";
$shell_out = shell_exec("java -jar TEST.jar $arg1");
echo $shell_out;
?>
If I execute an R program through macOS Terminal it works fine, but if I execute that program through PHP exec() I get an error which says "Rscript not found".
submit.php:
<?php
// print "hello";
$a = $_POST['a'];
$b = $_POST['b'];
// echo shell_exec("calc");
$output = exec("Rscript /xampp/htdocs/demo/1.R ".$a." ".$b);
print $output
?>
1.R:
setwd("C:/xampp/htdocs/demo")
print("hello")
args=commandArgs(trailingOnly = TRUE)
a = args[1]
b = args[2]
c = as.numeric(a)+as.numeric(b)
cat(c)
You need to tell the command interpreter where Rscript is located. In a normal login, you'd have a long PATH variable to search through, but when running from PHP you have a much more limited path. To figure out where the executable is located, type which Rscript from Terminal. Use the resulting path in your PHP script.
Also note that dumping raw user input into shell commands is a very bad idea. You should always use escapeshellarg() to make sure the input is sanitized. I would also suggest capturing the full output in the event that R outputs more than one line.
<?php
$a = escapeshellarg($_POST["a"]);
$b = escapeshellarg($_POST["b"]);
$r = "/xampp/htdocs/demo/1.R";
$lastline = exec("/usr/local/bin/Rscript $r $a $b", $output, $return);
// you could check the value of $return for non-zero values as well
// full output is returned as an array
echo implode("\n", $output);
Finally, you'll want to check your setwd() command in the R script. Might have some trouble with C: on a Mac! ;)
I have the fallowing code
<html>
<body>
<?php
if ($_GET['run']) {
# This code will run if ?run=true is set.
echo "Hello";
exec ("chmod a+x ps.sh");
exec ("sh ps.sh");
}
?>
<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
Click Me!
Now i want to know exec ("chmod a+x ps.sh") is executing properly or not. What should i do??
Have a look at the documentation:
string exec ( string $command [, array &$output [, int &$return_var ]] )
...
return_var
If the return_var argument is present along with the output argument,
then the return status of the executed command will be written to this
variable.
So just check if the return code is not equals zero:
exec ("chmod a+x ps.sh", $output, $return);
if ($return != 0) {
// An error occured, fallback or whatever
...
}
exec(..., $output, $return);
if ($return != 0) {
// something went wrong
}
Capture the return code by supplying a variable name for the third parameter. If that variable contains 0 afterwards, all is good. If it's anything other than 0, something went wrong.
exec() accepts other parameters. The second one is output, it allows you to see the output of your command.
In the case of a chmod, a correct output is nothing.
The third argument of exec() is the return status. It should be 0 in case of success.
You should then do something like :
exec ("chmod a+x ps.sh", $out, $value);
if(!empty($out) || $value != 0)
{
#there was an error
}
Note : you don't have to initialize $out or $value beforehand, PHP will create them as you use them.
I am unable to understand why the return value in php is not working. Can anybody help me?
<?php
exec("xyz.py",$output,$return);
foreach($output as $item){
echo "$item";
}
echo $return;
?>
The script of xyz.py is as follows:
def func():
print ('Hello')
return 21
func()
The output is always Hello0 no matter what value xyz.py returns
Thanks in advance.
According to the PHP docs, the third argument of exec, ($return in your example), works like this:
If the return_var argument is present along with the output argument, then the return status of the executed command will be written to this variable
Since your python program ran fine, the return status should be 0 (no errors).
This might be what you want:
import sys
def func():
print ('Hello')
return 21
sys.exit(func())
Return parameter denotes the status of the exec() function and NOT what the program returns .
-1 = error
0 = success
Append this to your execution string, which allows you to capture any error output:
2>&1 &
So as per your example:
exec('xyz.py 2>&1 &', $output);
echo $output;
I have a python script that returns a json object. Say, for example i run the following:
exec('python /var/www/abc/abc.py');
and it returns a json object, how can i assign the json object as a variable in a php script.
Example python script:
#!/usr/bin/python
import sys
def main():
data = {"Fail": 35}
sys.stdout.write(str(data))
main()
Example PHP script:
<?php
exec("python /home/amyth/Projects/test/variable.py", $output, $v);
echo($output);
?>
The above returns an empty Array. Why so ?
I want to call the above script from php using the exec method and want to use the json object returned by the python script. How can i achieve this ?
Update:
The above works if i use another shell command, For Example:
<?php
exec("ls", $output, $v);
echo($output);
?>
Anyone knows the reason ?
If the idea is you'll have a Python script which prints JSON data to standard out, then you're probably looking for popen.
Something like...
<?php
$f = popen('python /var/www/abc/abc.py', 'r');
if ($f === false)
{
echo "popen failed";
exit 1;
}
$json = fgets($f);
fclose($f);
...will grab the output into the $json variable.
As for your example Python script, if the idea is you're trying to convert the Python dictionary {"tests": "35"} to JSON, and print to standard out, you need to change loads to dumps and return to print, so it looks like...
import simplejson
def main():
data = simplejson.dumps({"tests": "35"})
print data
main()