Using R through PHP Using R through PHP r r

Using R through PHP


Couple of points:

  1. You want --slave as the option, it implies --no-save and turns the greeting off; see the manual for more.

  2. What you really want is Jeff Horner's excellent R-inside-Apache, see here for more. It can use templating frameworks like brew as well. Best of all, Jeff now provides a .deb package for you: use deb http://ppa.launchpad.net/jeffreyhorner/rapache/ubuntu lucid main in /etc/apt/sources.list.

  3. If you insist on piping from php, consider the littler scripting frontend Jeff and I wrote. It will start faster than R.


For something this simple, you shouldn't even use PHP, 'cause you can do it solely with RApache, brew package and plain HTML (CSS/JS are optional). Just read the RApache manual and see Jeroen Ooms' video tutorial. You should also read brew manual. Jeff really did a great job!

In a nutshell, you just need to setup apache2.conf or .htaccess file. Instead of using <Directory> or <Location> directives, you can use <FilesMatch> directive so you can match files with regexpr. Here's a sample .htaccess:

<FilesMatch "^.+\.rhtml$">    SetHandler r-script    RHandler brew::brew</FilesMatch>

I use special file extension .rhtml where I mix HTML with R syntax within <% and %> tags (see brew documentation). I didn't use brew with PHP, 'cause brew with HTML did the trick.

Anyway, you said that you want to:

write a page in PHP that contains a command I would like to execute in R and then pass the results back to be able to work with them

  • about executing commands from user input... well... don't do it! Especially don't allow users to execute custom commands 'cause they can easily pass system or file.* commands and mess your system up! You can use AppArmor, but it's still a long way down...
  • focus on simple HTML forms and use POST, GET, COOKIES, FILES and SERVER variables that RApache provides, and then manipulate inputs within R script
  • about "passing the results back", you can use either XML R package, or rjson (my favourite, and I recommend it). Then you can pass R object to toJSON function and unserialize it with JavaScript. Of course, that's true only if your clients are web-browsers, otherwise, if you, say, want to pass some info to embedded system, you should use the standard XML-way
  • for something this simple, you don't need PHP. Anyway, you should contact Jeroen, I know he used some PHP in his Stockplot application

For any further questions, use RApache mailing list.

...and hello R-webdev world! =)


Whatever user apache is running as may not have the same environment variables, or permissions as when you ran it from the shell by hand. Find out what user apache runs as, and make sure it has the right permissions and environment variables.