Cannot Run Rscript from PHP but it runs perfect from terminal

I’m new to Ubuntu
I’m trying to execute an Rscript in PHP using exec. However it doesnt run.
When I run it from the terminal it executes perfectly.

This is the code I run from commandline:

/usr/lib/R/bin/Rscript /home/xin/Documents/ClassificationApp/ClassificationAllInOne.R "http://localhost/categorisation/public/classification/data/1423242832.json"

It works perfectly.

From searching around i can deduce it is a permissions issue as PHP/apache runs as www-data and Rscript is root.

I’ve tried a number of ammendments to the Sudoers file none of which worked:-

User_Alias WWW_USER = www-data
Cmnd_Alias WWW_COMMANDS =  /usr/lib/R/bin/Rscript, /home/xin/Documents/Classifi$

WWW_USER ALL = (ALL) NOPASSWD: WWW_COMMANDS

This hasn’t worked. I’ve spent a day messing around with various combinations. It’s driving me mad.

Any inspiration would be most welcome

M

Asked By: user2987739

||

When debugging PHP code that executes external scripts (R, bash, …) the easiest thing to do is to install php-cli

sudo apt-get install php-google-api-php-client 

php-cli means “PHP Command Line Interface”. As the name suggests, it’s is a way of using PHP from the terminal.

then execute the script using /usr/bin/php -q <?php YourPHPCodeHere; ?>

Alternatively, create a file that contains the PHP code:

#!/usr/bin/php -q
<?php
echo "Hello world...";
?>

then chmod +x szNameOfFile

and then just type ./szNameOfFile

If you don’t want to type the full path to your PHP script, just create a bin directory in your home directory and copy all your script files there (this directory automatically gets added to the path after you exit and re-open your terminal)

Answered By: Fabby

So I know this is and old post.
But I just ran into the same issue and unfortunately the solution above didn’t work for me. (sorry I’m not very familiar with Linux so excuse the lack of correct terminology)

So if anyone run into the same issue:

  1. I ran this in PHP system("/lib/R/bin/Rscript /var/www/html/my_r_file.R 2>&1");
  2. I got an error that library sf wasn’t installed
    So the issues was that I wasn’t the root user when installing the packages.
    S do the following:

sudo -u su -i

Then install all the libraries you need.

I hope this can help someone avoided a day of frustration.

Answered By: Jcstay