1

I want to execute a R script (named script.R) within PHP code with an Apache Web Server. Here is my R code : I install packages then import data then I can proceed a classification tree on the data:

library(lubridate)
library(plyr)
library(rpart)
library(sqldf)
library(survival)
library(randomForest)
library(rpart.plot)

data=read.table(file = "t.txt",header = T,sep = ";",stringsAsFactors = T)

input=read.table(file = "file.txt",header = T,sep = ";",stringsAsFactors = T)

tree=rpart(sat~.,data,method="class")


png("tree.png", width=1000, height=800, antialias="cleartype")
plot(tree, uniform=TRUE,
     main="Classification Tree")
text(tree, use.n=TRUE, all=TRUE, cex=0.8)

dev.off()

My php script must execute this R script. They are placed in "C:\Apache24\htdocs" with "file.txt" and "t.txt"

So my php file consists in :

<?php
exec("Rscript script.R", $results);
print_r($results);
?>

But I get "Array()"

Any idea?

2
  • 1
    Try using passthru() to get all of the output. exec() only returns the last line: php.net/manual/en/function.passthru.php Commented Jul 6, 2016 at 17:08
  • Same results ! It get return "1". I suppose that means that the execution worked but i dont have the plot ("tree.png") . Maybe R is not installed on the server. How could I check if it is? Commented Jul 7, 2016 at 7:39

1 Answer 1

1

Install required R packages in system-wide location. On my machine this requires:

$ sudo R
> install.packages("Rpkg", lib = "/usr/local/lib/R/site-library/")

Explanation:

I see you have installed couple of R packages. And I'm guessing that you have installed them in default location i.e. user home directory.

So if you try to execute your R script from command-line, something like:

$ php foo.php  

You'll see that the script gets executed successfully (assuming rest of the code is bug free) and the script.R gets called as expected.

But this will fail when you try to execute php from apache. The reason is that since you have installed R packages in home directory they are inaccessible to www-data, the user which executes php under apache.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.