"; echo "Number ...">

R and php integration

I am trying to run an R script from php using the following:

echo "<form action='poorman.php' method='get'>"; echo "Number values to generate: <input type='text' name='N' />"; echo "<input type='submit' />"; echo "</form>"; if(isset($_GET['N'])) { $N = $_GET['N']; // execute R script from shell // this will save a plot at temp.png to the filesystem exec("Rscript my_rscript.r $N"); // return image tag $nocache = rand(); echo("<img src='temp.png?$nocache' />"); } 

and my R script is as follows:

 args <- commandArgs(TRUE) N <- args[1] x <- rnorm(N,0,1) png(filename="temp.png", width=500, height=500) hist(x, col="lightblue") dev.off() 

Does not generate temp.png

The r script is fine, but it seems like I cannot execute this script with php. Any help would be greatly appreciated?

Note. I am using ubuntu. Thanks,

+4
source share
2 answers

Yes, you can call R from PHP and get its output. If the script that you offer for demo purposes is fine, but if you intend to use this script on a web page, keep in mind that there is never a good security practice to make a system call using form input. This can be done with several very serious injections.

If you are sure that the Rscript executable is in your path and will provide a FULL PATH for my_rscript.r (and not just the script name, since PHP can execute the command from a different path where R and scripts may be), you can use the following recommendations for receiving standard script output and standard error (and also standard input, which will allow you to pass input not from the command line, but directly from R stdin:

check output php exec always returns empty array

+5
source

exec (". \ R \ R-3.1.3 \ bin \ Rscript. \ R \ R-3.1.3 \ bin \ my_rscript.R $ N"); copy the r folder and put it in the same directory as you would expect if I use xxamp, and then paste the R folder into htdocs.

+1
source

All Articles