Executing python commands from php script - php

I have installed SymPi in the server and from the command line, I am able to execute the following.
python ./sympy-0.7.5/bin/isympy
(this will open a console where I can type mathematical expressions. then the following expression)
1 + 2
(will give 3 as output)
My aim is to do the same from php using shell_exec. I have written a php file as given below, but is not working.
$command = escapeshellcmd('python ./sympy-0.7.5/bin/isympy');
shell_exec($command);
$output = shell_exec('1 + 2');
Can anybody help me to figure out why this is not working?
Please note that the following script works fine which just execute a python script and retrieve the output.
$command = escapeshellcmd('python C:\PythonPrograms\test3.py');
$output = shell_exec($command);
echo $output;

My guess is that the working directory (cwd) of shell_exec is different from the one you're in when you execute it manually.
Your working example specifies a hard path that will work from anywhere. Whereas your not-working example specifies a relative path (./ is the cwd).
Convert your call to isympy to give its full path on disk. Or figure out how to set the cwd of shell_exec.
(If this doesn't solve it, say more than "is not working." What happens? An error? What is the full text of the error?)

Each time you run shell_exec, it opens a completely new instance of the shell.
Edit:
You can pass a command for python to execute like this:
$expression = '1 + 2';
$cmd = 'python -c \'print "%f" % (' . $expression . ')\'';
$output = shell_exec($cmd);
This, admittedly is not using sympy, but for simple mathmatical expressions you may not need to. If you do, you would just need to import the library in the same command, like this: python -c 'import sympy; print "%f" % sympy.sqrt(3)'

I could manage the desired result in a different way.
Created a python script which accepts the expression as the command line argument , execute and display the output.
Call this script from php by passing the expression as the command line argument.

Related

PHP exec returns empty string while executing Python script

I am trying to run a Python script inside PHP and show the output.
I tried with simple test.py inside PHP, which print hello world without problem. But when I try to execute my desired command from PHP script the exec() returns empty string instead of output.
So the here is my php script. Below snippets works fine:
$output = exec("python test.py");
var_dump($output);
But not the desired one.
$command = "python -m scripts.label_image --graph=tf_files/retrained_graph.pb --image=".$uploadfile;
$output = exec($command);
var_dump($output);
so the folder structure is:
/var/www/mysite/
-scripts(folder which contains python scripts)
-tf_files(folder with other files)
-uploads (image folder)
Can someone tell me what is going wrong?
Sample output in stdout/shell:
the variable $output should an argument.
If you do this, you should get only the last output of your script.
exec("python test.py", $output);
var_dump($output);
https://www.php.net/manual/en/function.exec.php

Unable to call a python script through PHP

I Have been stuck for a couple of days now. I am attempting to call a simple python script from PHP. For the life of me I cannot figure out what the issue is. I have made the onoff.py script executable with chmod +x.
I can run the script just fine from the command line like this:
pi#raspberrypi:/var/www/html $ python onoff.py
LED on
LED off
My issue is when I try to call the script from PHP. I get nothing.
My Python Script:
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
My PHP Script:
<?php
$command = escapeshellcmd('python /var/www/html/onoff.py');
$output = shell_exec($command);
echo $output;
?>
Any help is greatly appreciated!
EDIT:
if I change my onoff.py script to a simple while loop such as:
#!/usr/bin/python
x=1
while (x<10):
print x
x=x+1
the output on the browser is:
1 2 3 4 5 6 7 8 9
I just don't understand why the loop will run but I get no output with the original python code.
EDIT 2:
Ok So I taking a different approach and trying to see where the code fails. I am adding bits of code at a time. Please see the following.
#!/usr/bin/python
import random
import time
import RPi.GPIO as GPIO
randomNumber = random.randint(1, 20)
GPIO.setmode(GPIO.BCM)
#GPIO.setup(18,GPIO.OUT)
print randomNumber
Now when I run the PHP it shows a random number so I know the python script is running. When I un-comment GPIO.setup(18,GPIO.OUT) and run the php I get a blank screen. I have no idea why this would make the script fail.
shell_exec() will only return a string if $command a). Ran OK and assuming b). that it spits its response to STDOUT.
Use exec() and pass it your command, an integer $code and an empty array $response both of which are treated by PHP as arguments by reference.
Run your command thus:
$command = escapeshellcmd('/path/to/python /var/www/html/onoff.py');
$response = array();
$code = 0;
exec($command, $response, $code);
var_dump($code, $response);
die;
You should now see what is actually being given to PHP internally and why the Python script isn't working.
You need to use python before the script, i.e.:
$command = escapeshellcmd('python /var/www/html/onoff.py');
If it doesn't work, python probably ins't on the PATH of the apache user and you may need to use the full path to the python binary, use which to find the full path:
which python
//usr/bin/python
The use that value:
$command = escapeshellcmd('/usr/bin/python /var/www/html/onoff.py');
Note:
Make sure apache user has execute permissions on onoff.py

GetOpt doesn't read full URL

I have a script that need to run from a terminal or a command prompt. I'm using PHP. GetOpt is the function that I use to get data or a parameter that the user input in the terminal.
This is my script.
<?php
$opt = getopt("f:");
$input = $opt['f'];
$u = fopen($input, 'r');
echo "\n\n$input\n\n";
I tried to run it like this:
$ php myscript.php -f http://myurl.com/file.csv?city=london&status=3
My url is http://myurl.com/file.csv?city=london&status=3, but it only outputs http://myurl.com/file.csv?city=london. The status parameter is lost from the full URL.
How can I get this to work?
it's because you have to wrap your link around into quotes:
$ php myscript.php -f "http://myurl.com/file.csv?city=london&status=3"
I'll go ahead and assume you are running your script in Bash, and & in Bash might be interpreted as bitwise AND in your case:
$ echo $(( 98 & 7 ))
2

PHP variable into Python

I understand there are questions like mine already asked, but I can't figure this out even with the answers in those questions.
PHP:
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py'.$var1);
?>
Python:
import sys
print(sys.argv[1])
Error received when running in Python:
IndexError: list index out of range
Both scripts are in the same folder.
Could someone please provide an answer with the code changes?
Error
If the Python script runs with no arguments at all, then that sys.argv[1] index is out of range.
Scripts
ExecPython.php
<?php
$var1 = "hi";
$result = shell_exec('TestingStuff.py ' . $var1);
echo "<pre>$result</pre>";
TestingStuff.py
import sys
if len(sys.argv) > 1:
print(sys.argv[1])
Demo
Explanation
We will start with the Python script. The goal is, that the script prints the first argument passed to it - without running into the "IndexError: list index out of range" error.
python TestingStuff.py 123 we want the output 123.
In Python the arguments passed to the script reside in sys.argv. It's a list. sys.argv[0] is always the script name itself (here TestingStuff.py). Using the example from above sys.argv[1] is now 123.
Handling the edge cases: "no argument" given.
python TestingStuff.py
This will result in an "IndexError: list index out of range" error, because you are trying to access a list element, which is not there. sys.argv[0] is the script name and sys.argv[1] is not set, but you are trying to print it and BAM goes the error. To avoid the error and only print the first argument, we need to make sure, that the list sys.argv contains more than one element (more than the script name). That's why i've added if len(sys.argv) > 1:.
That means: print the first argument only, if the list has more than 1 argument.
Now we can test the Python script standalone - with and without arguments.
And switch over to the PHP script.
The goal is to execute the Python script from PHP.
PHP provides several ways to execute a script, there are for instance exec(), passthru(), shell_exec(), system(). Here we are using shell_exec(). shell_exec() returns the output of the script or command we run with it.
In other words: if you run $result = shell_exec('php -v');, you'll get the PHP version lines in $result.
Here we are executing the Python script TestingStuff.py and add an argument, which is $var1. It's a string and added via concatenation to the string given to shell_exec(). The $result is echoed. I wrapped pre-tags around it, because i thought this is executed in the web/browser context. If you are using the scripts only on the CLI, you might drop the pre-tags.
Execution flow
the PHP script is executed
shell_exec() executes the Python script
shell_exec() returns the output of the Python script as $result
$result is printed by PHP via echo

How to run Java program and get output in PHP?

I'd like to run something like (in myProgram.sh):
java -cp whatever.jar com.my.program $1
within PHP and read the output.
So far I have something like:
$processOrderCommand = 'bash -c "exec nohup setsid /myProgram.sh ' . $arg1 . ' > /dev/null 2>&1 &"';
exec($processOrderCommand);
But what I'd really like is to be able to get the output of the java program within the PHP script and not just execute it as another thread.
How can this be done?
You can do this :
exec($processOrderCommand, $output);
From the documentation :
If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().
For a better control on your execution you can take a look at proc_open()
Resources :
php.net - exec()
php.net - proc_open()
The key is that the classpaths need to be absolute within the shell_exec
PHP script.
Or at least that's the only way I could get it to correctly work. Basically it's almost impossible to tell from environment to environment what the relative directory is that the php script is running the JVM.
As well, it helped to put the absolute path location for java, such as usr/.../bin/java

Categories