Sending value from R to php - php

I have this code in the .php file:
$nb1 = 1;
$nb2 = 2;
exec("C:/xampp/phpR/plotR.r $nb1 $nb2", $response);
echo $response;
And I have in the .r file:
args <- commandArgs(TRUE)
x<-args[1]+args[2]
print(x)
The php code prints "array" on browser. It should print "3". It prints "array". Where are the problem?
Thanks

PHP is interpreting the response from your R script as an array, whether the R script is actually returning an array I'm not sure. Regardless, if you do var_dump($response) you'll likely get something like
array (size=1)
0 => int 3
I think you should be able to substitute echo $response[0]; for echo $response; and get the results you need.

If anyone else happens upon this unanswered question, I had the same problem, and it turned out to be a permissions issue. The user that my webserver was running as didn't have permission to run my R script.
This can be diagnosed by following the excellent directions at:
How to retrieve PHP exec() error responses?
and viewing the error.
To get things to work nicely, I also changed the output of my R script from print(x) to write(x, stdout()). While print(x) would give you [1] 3 as an output, write(x) would return 3.

Related

PHP exec() Output Cut Short

I have a PHP file that runs a node script using exec() to gather the output, like so:
$test = exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/");
echo $test;
It outputs a JSON string of data tied to the website in the --url paramater. It works great, but sometimes the output string is cut short.
When I run the command in the exec() script directly, I get the full output, as expected.
Why would this be? I've also tried running shell_exec() instead, but the same things happens with the output being cut short.
Is there a setting in php.ini or somewhere else to increase the size of output strings?
It appears the only way to get this working is by passing exec() to a temp file, like this:
exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/ > /home/user/www/uploads/json.txt");
$json = file_get_contents('/home/user/www/uploads/json.txt');
echo $json;
I would prefer to have the direct output and tried increasing output_buffering in php.ini with no change (output still gets cut off).
Definitely open to other ideas to avoid the temp file, but could also live with this and just unlink() the file on each run.
exec() only returns the last line of the output of the command you pass to it. Per the section marked Return Value of the following documentation:
The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.
To get the output of the executed command, be sure to set and use the output parameter.
https://www.php.net/manual/en/function.exec.php
To do what you are trying to do, you need to pass the function an array to store the output, like so:
exec("/usr/local/bin/node /home/user/www/bin/start.js --url=https://www.example.com/", $output);
echo implode("\n", $output);

Python to PHP strange error

I hope somebody can help me. :)
I am calling a python script from PHP, with the help from phpseclib/ssh2 i ssh into my server and it works fine.
My problem is that if i use "time.sleep(5)" in the loop of my python script i dont get a result back, but if i remove time.sleep(5) and time.sleep(3) it works.
Anybody have an idea why this happen?
If i try the python script i my console everything is picture perfect.!
items = [
'1',
'2',
'3'
]
itemArray = {}
def checker():
for item in items:
time.sleep(5) # If added not working, if removed working, result gets send back
position = 1 # keeps track of the ranking position
for start in range(int(deep)):
time.sleep(3)
results = 'something'
for div in results:
try:
if div.find('i', href=True)['href'].find(something) != -1:
exit_conditon = True
break
else:
position += 1
except:
print "Unexpected error:", sys.exc_info()[0]
raise
if 'exit_conditon' in locals():
if exit_conditon is True:
exit_conditon = False
itemArray.update({value: 1})
break
sys.exit(itemArray)
checker()
Please help.
Update: if i have 3 rows in the items array i need to remove the second time.sleep(5) to get it working, if i have 2 items in my array i only need to remove the first time.sleep(5).
It depends how long your script take time to execute. If your script (php + python) take longer than 30 second with the default config, them php kill it.
Just add set_time_limit(120) at the beginning of your php code
See http://php.net/manual/en/function.set-time-limit.php
And If you are executing the php and python script on the same server you should use exec or shell_exec. It will be faster this way. See php shell_exec() vs exec()
The script is now working as i should do :) Thanks to "neubert" for the answer.
If i set the $ssh->setTimeout() to unlimited, whould i still get a respons if the script halts at some point?

Echo Exec ("python filepath $variables") Not Working

I have a bit of backend code that is executed like so:
python filepath $inputvariable
This code prints out some data. As you can see in the screenshot below, when I run this code through terminal it works flawlessly, outputting the expected value:
CHI 110^*^Integrated Chinese Level 1 Part 1^*^https://www.amazon.com/Integrated-Chinese-Simplified-Characters-Textbook/dp/0887276385/ref=sr_1_1?ie=UTF8&qid=1466983577&sr=8-1&keywords=integrated+chinese^*^47.49
But I run into issues when I try to run the same code through php:
echo exec ("python /Users/USERNAME/Desktop/Exeter_Bookstore_Project/localserver/cont/Scripts/Python/serverside.py $classToSend");
This code returns a null value. At first I assumed that I wasn't passing variables through correctly, but echo $classToSend; yielded the correct variable. Then I tried having the php execute a hello world python script, but this also worked proving that the issue wasn't in my python interpreter. Then I thought that maybe the python script wasn't forwarding data quickly enough, but the helloworld.py still worked even with a time delay of 3 seconds.
Does anyone have any idea of what I might have done wrong, or do you need more information. Any help will be greatly appreciated.

How to display the output of a system command in browser exactly as in terminal

I used php shell_exec to run BLAST command (biologcal sequence alignment tool) and outputs the result in browser. However, I am not able to format the result same like it displayed when I run the same command in terminal . I tried using methods like passthru() and exec(). Both of it doesnt work! In my case, output formatting is important as a small space can make the error (a portion is give below). Can anyone tell me how to display the result in browser as exactly which in command terminal.
$cmd = "$blast -query /var/www/html/kim/blast/testing.txt -db /var/www/html/kim/blast/$db";
$result =shell_exec($cmd);
print_r ($result);
Part of my output looks like,
Query 707 TCAGACTTGAA 766
|||||||||||
Sbjct 3632 TCAGACTTGAA 3691
In order to keep formatting identical, including spaces etc., you should use the <pre> html element. An example:
echo '<pre>';
echo $result;
echo '</pre>';
Just echo the raw result. Using print_r or var_dump would lead to formatting by PHP. The above example is the most raw formatting you can achieve, given you leave result untouched.
With CSS you can then style the <pre>. But make sure to use a MONOSPACE font so that shell formatting is kept.

python 2.6.5, and getting the result of a call to a php app

i've got this snazzy python code:
import subprocess
value = subprocess.Popen(["php","./php/php_runner.php"],stdout=subprocess.PIPE);
the problem is, i have no idea how to check if the php_runner, well, ran. Currently, it has the following salient sections:
if (count($argv) != 4){
die("four arguments are needed\n");
}
and
$returnValue = call_to_another_php_class();
return $returnValue;
So what i want is this:
How do i get the return value, whatever it may be, using python?
You probably are going to tell me to use "PIPE" in the answer, but the (to me, incomprehensible) python docs (http://docs.python.org/library/subprocess.html) state:
Do not use stdout=PIPE or stderr=PIPE with this function. As the pipes are not being read in >the current process, the child process may block if it generates enough output to a pipe to fill up >the OS pipe buffer.
So what do i use then, because while I don't really know what they're barking on about, i sit up and take note about notes in grey boxes. Pity they didn't spell out what i'm meant to do - but, well, what am i meant to do?
the "returnValue" that my php code returns, is that what python is going to pickup as the return value from the function? If not, how do i return that value?
cheers!
UPDATE
Thanks to the given answer, here's the changes i made:
edited /etc/php5/cli/conf.d/mcrypt.ini (actually, this is just a change for ubuntu 10.04, and I changed the first line to begin with a ; instead of a #. That stopped an annoying "we don't like #" error that kept popping up)
in my php, I changed the code to read:
if (count($argv) != 4){
fwrite(STDERR, "four arguments are needed\n");
exit(1); // A response code other than 0 is a failure
}
this puts my error value as an error. the die() command wasn't doing that for me.
changed the python to read:
value = subprocess.Popen(["php","./php/php_runner.php"],stdout=subprocess.PIPE,
stderr=subprocess.PIPE);
print value.communicate();
Yeah, realistically, i'd do an if on value.communicate()[1], becase that is where the errors are.
$returnValue = call_to_another_php_class();
if ($returnValue == 1){ //hah, php has a good return value as 1.
//no problem
} else {
fwrite(STDERR,get_error_from_php_class());
exit(1);
}
booyah!
Since you're using the Popen constructor rather than the call functions, those notes about PIPE don't apply to you.
Use .communicate() as documented to wait for the program to finish and get the output.

Categories