2

I am trying to execute the following simple R script via PHP but I am always getting exit code 1 if I put library() function call.

library('optparse')
quit()

The PHP script 'test.php' is given as:

<?php
$calc = exec("Rscript test.r", $R_output, $R_exitcode);
print $calc_routine;

The script produces exit code 0 when I remove library() function call, so it's sure that R script is located correctly.

8
  • What is the content of $R_output? Is the package optparse installed in R (wherever you run your php script on)? Commented Jan 18, 2018 at 5:28
  • @Linus $R_output is an empty array and yes I can load the library 'optparse' in an interactive session. Commented Jan 18, 2018 at 5:30
  • What's the exit code when you call R from elsewhere? In what environment (CLI or webserver) does the PHP code run? Commented Jan 18, 2018 at 5:33
  • @UlrichEckhardt I am not sure if I understood the question completely but if I run the same script using Rscript, then the exit code is 0 (checked using ''$ echo $?''). The PHP code is running under XAMPP webserver. Commented Jan 18, 2018 at 5:35
  • So, what if you call PHP from the commandline and calls R from PHP in turn? Commented Jan 18, 2018 at 5:47

1 Answer 1

1

There is an environment variable called R_LIBS_USER that tells R where to look for libraries. By default, it is set to a subdirectory in your home directory. Of course when called from a web server, you will be not be running it – the home directory will be different.

First you'll need to determine what your library directory is. From R, call .libPaths() to get it.

Then, you can either tell PHP about the updated value:

<?php
setenv("R_LIBS_USER", "/path/to/your/libraries");
$calc = exec("Rscript test.r", $R_output, $R_exitcode);

Or, in your R code, use .libPaths with a parameter to set the library path to the new value:

.libPaths('/path/to/your/libraries')
library('optparse')
quit()
Sign up to request clarification or add additional context in comments.

1 Comment

good call. when php exec calls are mysteriously failing, environment variables being set to something unexpected is always a good place to start looking

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.