index.php
:
<?php
echo exec("Rscript foo.R");
?>
foo.R
:
#!/usr/bin/env Rscript
print("Before!")
#library(rJava);
print("After!");
Output on webpage:
[1] "After!"
Now this is an expected output as exec
returns the last line from the result of the command.
Now since I want to access the mongodb database which needs rJava
and RMongo
libraries I modified the above code a little bit.
foo.R
:
#!/usr/bin/env Rscript
print("Before!")
library(rJava);
print("After!");
Output on webpage:
[1] "Before!"
Now I don't understand this output. I expected the same output as before i.e [1] "After!"
. It's as if the R code starting from the library import line doesn't exist at all. I have tested the above code (and the omitted one where I use kmeans
on the data grabbed from mongodb
) in R shell
and it works as expected.
What's wrong with importing a library in a R
script which is meant to be executed from PHP
?
Update 1:
Interestingly, the modified foo.R
gets invoked and executed as per my expectation if I invoke index.php
from command line.
$ php index.php
Loading required package: methods
[1] "After!"
So my conclusion is that my normal user account can execute index.php
which in turn can load libraries in foo.R
but it seems www-data
user account has no permissions to load libraries in R
.
So now the question is how do I give permissions to www-data
to load R
libraries?
Update 2:
I solved this issue temporarily by changing apache user from www-data
to my current user but I'm aware this is a huge security risk and I'm looking for an alternative solution.