Jorge pulido lozano
Jorge pulido lozano

Reputation: 41

Conecting R with php

I am trying to run a code of R in php localhost way; so I followed this example (https://www.r-bloggers.com/integrating-php-and-r/).

<?php
// poorman.php

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 the R script…

# my_rscript.R

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()

I have both files in /var/www/html/R folder; when I ran the php file goes perfectly but que I submit the number of "N" it did not show the same as the example web image.

I also tried to run only to show a rnorm() distribution but I have the same results -> nothing.

I think that my problems is in coneccting R with php so I tried installation Rapache (http://rapache.net/manual.html) but when I reach "sudo apt-get install apache2-prefork-dev apache2-mpm-prefork libapreq2-dev r-base-dev" I received the following message -> could not find package apache2-prefork-dev

Any solutions?

Thanks in advance

George

Upvotes: 3

Views: 1171

Answers (1)

Parfait
Parfait

Reputation: 107652

Recreating your issue, the Apache error log returned:

'Rscript' is not recognized as an internal or external command, operable program or batch file.

This indicates the Apache server does not recognize the system environment variables. You might be running Apache in a different environment than your OS where most likely you have Rscript in your PATH variable. See how to set system environment variables in Apache which may involve adjusting the httpd.conf or .htaccess files.

However, consider the quick resolution in pointing to absolute path of the Rscript executable:

exec("path/to/R/bin/Rscript my_rscript.R $N");

For me, doing so yielded the appropriate output:

RScript Plot Output

Upvotes: 1

Related Questions