JFR
JFR

Reputation: 1

Can't execute RScript from php

New here, also new to coding with php. I am currently trying to execute an RScript from php using the exec() function. When i run the php code in localhost it opens RStudio program but does not execute the code in the script. (This makes me think it isn't a directory problem because it can actually locate the file) Here is the classical example i tried. Php code:

<html>
  <head>
    <h1>PHP and R Integration Sample</h1>
  </head>
  <body>
        <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
    exec("RvsPHP.R");
    ?>
    <img src="test.png?var1.1" alt="R Graph">

  </body>
</html>

Then, my Rscript (saved as "RvsPHP.R" in the same directory):

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

I am not interested in the output of the Rscript, just that it is executed (i.e. creates the .png image) Note: once the exec() opens the file with RStudio if i manually hit ctrl+enter and execute the script, the .png image is created and everything works just fine. If i don't do this, RStudio is left open with nothing going on and the browser is left loading until it reaches the timeout. I can't find the way to avoid the manual part of pressing ctrl+enter. I have also tried with passthru() and system() php functions with no luck.

Thanks in advance! Regards, JuanFran

Upvotes: 0

Views: 703

Answers (2)

JFR
JFR

Reputation: 1

Now it works, this does not mean that it is the best way, open for suggestions!

(As they mentioned RStudio is just the interface program)

Here is what made it work:

I changed the file extension from .R to .Rscript. The php code remained the same except for the exec() part which now is: exec("RvsPHP.Rscript");

The shebang doesn't seem to affect it (Tried both with and without), but is probably a useful concept for a web server execution as they mention. (?) I also added the RScript.exe and R.exe files as an environment variable, not sure if that did something as well.

Definetely the game changer was to change the file extension from .R to .Rscript (the default program that opens the file changes from RStudio to R) Thanks to all, JF

Upvotes: 0

Adam Winter
Adam Winter

Reputation: 1934

I'm going to take a wild guess here that: 1) Rstudio is not the program to execute Rscripts from, it's a program to help you write them. 2) You don't have a shebang in the script. So, you need to have Rscript installed so that you can execute the file with that environment, in which case your PHP code will read something like

exec("Rscript RvsPHP.R");

or you have a shebang in the script. Either way, you need to tell the machine what to execute that script with, and it needs to be something that is built to simply execute scripts.

Upvotes: 1

Related Questions