title: Executing R script from PHP
body: <p><code>index.php</code>:</p>
  
  <pre><code>&lt;?php
      echo exec("Rscript foo.R");
  ?&gt;
  </code></pre>
  
  <p><code>foo.R</code>:  </p>
  
  <pre><code>#!/usr/bin/env Rscript
  print("Before!")
  #library(rJava);
  print("After!");
  </code></pre>
  
  <p>Output on webpage:</p>
  
  <pre><code>[1] "After!"
  </code></pre>
  
  <p>Now this is an expected output as <code>exec</code> returns the last line from the result of the command.
  Now since I want to access the mongodb database which needs <code>rJava</code> and <code>RMongo</code> libraries I modified the above code a little bit.</p>
  
  <p><code>foo.R</code>:  </p>
  
  <pre><code>#!/usr/bin/env Rscript
  print("Before!")
  library(rJava);
  print("After!");
  </code></pre>
  
  <p>Output on webpage:  </p>
  
  <pre><code>[1] "Before!"
  </code></pre>
  
  <p>Now I don't understand this output. I expected the same output as before i.e <code>[1] "After!"</code>. It's as if the R code starting from the library import line doesn't exist at all. I have tested the above code (and the omitted one where I use <code>kmeans</code> on the data grabbed from <code>mongodb</code>) in <code>R shell</code> and it works as expected.</p>
  
  <p>What's wrong with importing a library in a <code>R</code> script which is meant to be executed from <code>PHP</code>?</p>
  
  <hr>
  
  <p><strong>Update 1</strong>:<br>
  Interestingly, the modified <code>foo.R</code> gets invoked and executed as per my expectation if I invoke <code>index.php</code> from command line.  </p>
  
  <pre><code>$ php index.php 
  Loading required package: methods
  [1] "After!"
  </code></pre>
  
  <p>So my conclusion is that my normal user account can execute <code>index.php</code> which in turn can load libraries in <code>foo.R</code> but it seems <code>www-data</code> user account has no permissions to load libraries in <code>R</code>.  </p>
  
  <p>So now the question is how do I give permissions to <code>www-data</code> to load <code>R</code> libraries?</p>
  
  <hr>
  
  <p><strong>Update 2</strong>:<br>
  I solved this issue temporarily by changing apache user from <code>www-data</code> to my current user but I'm aware this is a huge security risk and I'm looking for an alternative solution.</p>