I’m 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 the following :
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()
Its not generating the temp.png
The r script is fine but it seems that I cant execute this script from php. Any help would be greatly appreciated?
Note Im using ubuntu.
Thanks,
Yes, you may call R from PHP and get its ouput. If the script you propose is for demo purposes only is ok, but if you are going to use that script on a web page be aware that is never a good security practice to make a system call using input from a form. There are multiple and very serious injection attacks that can be done.
That being said, after being sure that Rscript executable is in your path and providing the FULL PATH to my_rscript.r (not just the script name, as PHP may execute the command from a different path where R & the scripts may be) you may use the following guidelines to grab the script standard output & standard error (ando also standard input, that will allow you to pass the input not from the command line but directly from R stdin:
check the output of php exec always returns empty array