1

I am trying to run a code of R in PHP, Here are my code :

index.php

<html>
  <head>
    <title>PHP and R Integration Sample</title>
  </head>
  <body>
    <div id="r-output" style="width: 100%; padding: 25px;">
    <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
      exec("Rscript sample.R");
    ?>
    <img src="test.png?var1.1" alt="R Graph" />
    </div>
  </body>
</html>

sample.R

x <- rnorm(6,0,1)
png(filename="test.png", width=500, height=500)
hist(x, col="red")
dev.off()

After that I found out that I got Apache Error like this :

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

I tried as the comments in this link Conecting R with php, and then I updated my code :

index.php

<html>
  <head>
    <title>PHP and R Integration Sample</title>
  </head>
  <body>
    <div id="r-output" style="width: 100%; padding: 25px;">
    <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
      exec("C:\Program Files\R\R-4.0.3\bin\Rscript sample.R");
    ?>
    <img src="test.png?var1.1" alt="R Graph" />
    </div>
  </body>
</html>

After that update I got this message in apache :

'C:\Program' is not recognized as an internal or external command,
operable program or batch file.

Anyone please tell me if I came wrong with interpreting the comments on the link I mentioned before. Please help me to implement R code in PHP, advise me for the best use case. Appreciate any answer.

ipipip
  • 11
  • 1
  • Think it should be something like `exec('"C:\Program Files\R\R-4.0.3\bin\Rscript" sample.R');` – Nigel Ren Feb 17 '21 at 16:53
  • Thankfully I don't get any error in my Apache, but I still got no result from "sample.R", any idea for that? @NigelRen – ipipip Feb 18 '21 at 12:53
  • To get all the output from the script, try `exec('"C:\Program Files\R\R-4.0.3\bin\Rscript" sample.R', $output);` and then see what `$output` contains. – Nigel Ren Feb 18 '21 at 12:59
  • I doing what you advise me, and here are the result : array(2) { [0]=> string(11) "null device" [1]=> string(11) " 1" } , but I still got no .png file in my folder @NigelRen – ipipip Feb 18 '21 at 13:02
  • I would assume that "null device" is something from the R script, have a look and see if there is anything on that. – Nigel Ren Feb 18 '21 at 13:04
  • Yes it is @NigelRen but the code in my R File supposed to create a png file for a histogram graph, when I ran a code `Rscript sample.R` in my CMD it was success, but when I came with exec() It's just going like what I mentioned before. What do you think about this issue? – ipipip Feb 18 '21 at 13:08
  • No idea, it may be worth asking a new question with this information and someone with R experience may be able to help. – Nigel Ren Feb 18 '21 at 13:13
  • @NigelRen Appreciate your help, Thanks a lot. – ipipip Feb 20 '21 at 18:18

0 Answers0