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?
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.
Related
I have a use case where i need to run a node module in php script and display it's output back on the page. Here's the steps I followed:
I have installed the module npm install -g md2gslides
I am using PHP's exec() for running the module
exec('node_modules/md2gslides/bin//md2gslides.js --version 2>&1', $output);
But it's not working. The error is below:
However, it runs in ubuntu's terminal without issues.
What is wrong here?
The error not because of php but because of the path.join() in line 33 of md2gslides.js
const STORED_CREDENTIALS_PATH = path.join(USER_HOME, '.md2googleslides', 'credentials.json');
It tries to find the credentials.json in users home directory. But I think it's unable to.
So I moved the file to node_modules/md2gslides/bin and modified path.join() as path.join(__dirname, '.md2googleslides', 'credentials.json')
This solved the issue.
I am attempting to run a R script from PHP. I have created a shelled out version of my code that produces the same error message. I am running in VSCode, PHP Version 7.3.9, and R-3.6.2. Below are shelled our versions of my code that demonstrate my issue.
index.php
<?php
$R = '"C:/Program Files/R/R-3.6.2/bin/Rscript.exe"';
$testScript = "C:/xampp/htdocs/rtest/testscript.r";
$command = "$R $testScript testingArguement 2>&1";
$result = shell_exec($command);
echo $result;
?>
testscript.r
## Define all libraries
suppressMessages(library(plyr))
suppressMessages(library(dplyr))
suppressMessages(library(tidyr))
suppressMessages(library(tidyselect))
suppressMessages(library(tidyverse))
suppressMessages(library(data.table))
## Suppress Warning Messages
options(warn=-1)
args = commandArgs(trailingOnly=TRUE)
testValue = args[1]
cat("The test value is",testValue)
When I run the command via PHP in VSCode, the result variable receives the following...
"Error in library(plyr) : there is no package called 'plyr'
Calls: suppressMessages -> withCallingHandlers -> library
Execution halted
"
However, if I run the command manually in Command Prompt it works.
C:\Users\Garrett>"C:/Program Files/R/R-3.6.2/bin/Rscript.exe" C:/xampp/htdocs/rtest/testscript.r testingArguement 2>&1
The test value is testingArguement
C:\Users\Garrett>
I am just super confused to why the packages aren't getting recognized when running from within VSCode/PHP
credit goes to Rscript: There is no package called ...?
but to summarize, I did the following
1) Start R.exe in command prompt, and type the following to get the location of where packages are installed Sys.getenv('R_LIBS_USER')
2) Paste the following line at the top of your R script so that Rscript.exe can reference
.libPaths(c(.libPaths(),pathFromStepOne))
I am working on a project where I want to use PHP and Phantomjs together, I have completed my phantomJs script and trying to run it using php exec function. but the function is returning an array of error list.
below I am writing my code of phantomjs and php
dir: /var/www/html/phantom/index.js
var page = require('webpage').create();
var fs = require('fs');
page.open('http://insttaorder.com/', function(status) {
// Get all links to CSS and JS on the page
var links = page.evaluate(function() {
var urls = [];
$("[rel=stylesheet]").each(function(i, css) {
urls.push(css.href);
});
$("script").each(function(i, js) {
if (js.src) {
urls.push(js.src);
}
});
return urls;
});
// Save all links to a file
var url_file = "list.txt";
fs.write(url_file, links.join("\n"), 'w');
// Launch wget program to download all files from the list.txt to current
// folder
require("child_process").execFile("wget", [ "-i", url_file ], null,
function(err, stdout, stderr) {
console.log("execFileSTDOUT:", stdout);
console.log("execFileSTDERR:", stderr);
// After wget finished exit PhantomJS
phantom.exit();
});
});
dir: /var/www/html/phantom/index.php
exec('/usr/bin/phantomjs index.js 2>&1',$output);
echo '<pre>';
print_r($output);
die;
Also tried with
exec('/usr/bin/phantomjs /var/www/html/phantom/index.js 2>&1',$output);
echo '<pre>';
print_r($output);
die;
After runing this i am getting below error
Array
(
[0] => QXcbConnection: Could not connect to display
[1] => PhantomJS has crashed. Please read the bug reporting guide at
[2] => and file a bug report.
[3] => Aborted (core dumped)
)
But if I run index.php file from the terminal like this:
user2#user2-H81M-S:/var/www/html/phantom$ php index.php
then it works fine.I don't know how to solve it. Please help.
i am using following version
system version: Ubuntu 16.04.2 LTS
PHP version: 5.6
phantomJs version: 2.1.1
Did you tried to set an environment variable on your server ? or added it before calling phantomjs ?
I was in the same situation and found some solutions:
a. define or set variable QT_QPA_PLATFORM to offscreen:
QT_QPA_PLATFORM=offscreen /usr/bin/phantomjs index.js
b. or add this line into your .bashrc file (put it at the end):
export QT_QPA_PLATFORM=offscreen
c. or install the package xvfb and call xvfb-run before phantomjs:
xvfb-run /usr/bin/phantomjs index.js
d. or use the parameter platform:
/usr/bin/phantomjs -platform offscreen index.js
Maybe you don't want / can't make modification on your server and in that case you may try to download the static binary from official website then:
/path/to/the/bin/folder/phantomjs index.js
and / or create an alias in your .bash_aliases file like this:
alias phantomjs=/path/to/the/bin/folder/phantomjs
make sure that phantomjs is not installed already on the system if you decide to use the alias.
if the file .bash_aliases not exist already, feel free to create it or add the alias line at the end of the .bashrc file
Some references:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=817277
https://github.com/ariya/phantomjs/issues/14376
https://bugs.launchpad.net/ubuntu/+source/phantomjs/+bug/1586134
I had the same problem running phantomjs on headless Ubuntu 18.04 (on the default Vagrant vm install of openstreetmap-website). Folloiwng Jiab77's links, it seems the Phantomjs team says the problem is the Debian package but the Debian team closed the bug as wontfix. I needed phantomjs to "just work" so it can be called by other programs that expect it to work normally. Specifically, openstreetmap-website has an extensive Ruby test suite with over 40 tests that were failing because of this, and I didn't want to modify all those tests.
Following Jiab77's answer, here's how I made it work:
As root, cp /usr/bin/phantomjs /usr/local/bin/phantomjs
Edit /usr/local/bin/phantomjs and add the line export QT_QPA_PLATFORM=offscreen so it runs before execution. Here is what mine says after doing so:
#!/bin/sh
LD_LIBRARY_PATH="/usr/lib/phantomjs:$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH
# 2018-11-13: added the next line so phantomjs can run headless as explained on
# https://stackoverflow.com/questions/49154209/how-to-solve-error-qxcbconnection-could-not-connect-to-display-when-using-exec
export QT_QPA_PLATFORM=offscreen
exec "/usr/lib/phantomjs/phantomjs" "$#"
After this change, phantomjs can be run from the command line without changing anything else, and all the tests that depend on phantomjs were successfully passed.
I am trying to run a PowerShell command from inside a php file on my webserver.
Here is my php code:
<?php
$query = shell_exec('C:\\Windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe -command Get-Host');
echo $query;
?>
The result I get is HTTP Error 500 - C:\PHP\php-cgi.exe - The FastCGI process exceeded configured activity timeout - Error Code 0x80070102
To perform a test to verify shell_exec and php were functioning (that I hadn't screwed something up when setting up the environment). I also tried this php:
<?php
$query = shell_exec('dir c:\\');
echo $query;
?>
This worked, the page source looked exactly like you'd expect if you had run the dir c:\ command from a command prompt in windows.
I've looked at several other articles here on stackoverflow, as well as on technet, and can't seem to identify what is causing this to time out. When I run the same command from the command prompt the result is very quick.
Here are the results from executing the same command manually at the command prompt (again what you'd expect):
C:\>C:\Windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -command Get-Host
Name : ConsoleHost
Version : 2.0
InstanceId : 9a24a372-f0a3-4a79-b9fd-1e180e9a8069
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
A little about my environment:
I'm running IIS 7.5 on a Windows 2008 R2 SP1 Standard Server.
The server is standalone (not part of a domain).
I have PHP 5.5.9 installed, and working. phpinfo() returns the expected page without any noticeable errors.
Any help in getting me on track with executing powershell commands from php is much appreciated!
Try this :
$query = shell_exec('C:\\Windows\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe -command Get-Host < NUL');
I am running Ubuntu 12.04 with the standard lampp stack with the l*calhost at var/www. There is a symbolic link ('git') to my eclipse workspace 'user/Documents/workspace'. I have set permissions for the workspace folders using 'sudo chmod 644 .' and in the httpd.conf in etc/apache2/sites-available I have changed it to read:
# User/Group: The name (or #number) of the user/group to run httpd as.
# It is usually good practice to create a dedicated user and group for
# running httpd, as with most system services.
#
#User daemon
User cjmartin
Group daemon
If I run an html file that does a callback to a php file on my remote server it works, but if I use the same php file in my eclipse workspace I get:
"Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://l*calhost/git/CrystalliseCalculators/CrystalliseCalculators.php?q={%…nd+Wales&searchTerms%5Bmodel_name%5D=Crystallise+model+1.0&_=138651239125"
Normal html files run normally from the worskpace, but not a php call.
I assume this is a problem with the permissions. Any ideas?
The callback code:
...
var path1 = "http://l*calhost/git/CrystalliseCalculators/"
...
function doIt(){
strSearch = "The search terms"
var theCalla = path1+"CrystalliseCalculators.php?q="+JSON.stringify(strSearch);
// Call the Crystallise API to fetch central mortalities.
$.ajax({
url:theCalla,
type:'GET',
dataType:"jsonp",
jsonp:"callback",
data:strSearch,
success:function(dataBack){
//Do stuff with the results....
},
error:function(errorData1){
alert("error msg"+JSON.stringify(errorData1));
}
});
};
This was not a permissions problem for the relevant files and folders as it turned out.
The problem was in a database call inside the php file that failed silently.