Click here to Skip to main content
15,393,863 members
Articles / Programming Languages / R
Posted 25 Aug 2016

Tagged as


11 bookmarked

Pass Arguments and Execute R script from PHP Forms: Discrete Event Simulation Example

Rate me:
Please Sign up or sign in to vote.
4.97/5 (13 votes)
2 Dec 2021CPOL3 min read
Discrete event simulation example
This is a simple tutorial illustrating steps required for running R script from PHP and passing arguments from web interface to be consumed by R and output the results to different files residing on Ubuntu Server with corresponding markup on PHP web page. An example of discrete event simulation is used.

Image 1


After the release of our latest article "Discrete Event Simulation using R: Hospital Capacity Planning", we got constructive feedback from our colleagues. In conclusion, there was a compelling request to create a simple user-friendly interface for non-programmers. Instead of having to modify the parameters of the simulation from inside R-studio, why not use a simple form to feed the needed parameters and avoid the "side effects" of accidentally modifying the core script during the process of setting the simulation parameters through manipulation of the original code.

To run the simulation mentioned in the given article, we will need a form that will take 4 numeric parameters and submit it to the PHP page that will pass the arguments and execute R script using shell_exec(). The output of R will be stored in a folder. A PHP script will iterate through all files in this folder and create links to it and will create image source HTML tags to the output graph and display it, along with links to output files, in the output page.

Image 2

Using the Code

The HTML Form

As mentioned above, we need to pass 4 arguments to the R script. We will use an HTML form to do the job. The user will enter the 4 values in the corresponding input fields and submit the form. The fom action will call runr.php with GET method.

Image 3

<!-- add the link to bootstrap CSS and JS libraries -->
<link href="" 
<script src="" 
<form class="form-horizontal" action="runr.php" method="get">
<!-- Form Name -->
<legend>Insert Simulation Parameters</legend>
<!-- Text input-->

<div class="form-group">
  <label class="col-md-4 control-label" for="nbeds">Number of beds:</label>  
  <div class="col-md-4">
  <input id="nbeds" name="nbeds" type="text" 
  placeholder="Number of beds" class="form-control input-md" required="">

<!-- Text input-->

<div class="form-group">
  <label class="col-md-4 control-label" 
  for="myrep">Number of repetitions:</label>  
  <div class="col-md-4">
  <input id="myrep" name="myrep" type="text" 
  placeholder="Number of runs" class="form-control input-md" required="">

<!-- Text input-->

<div class="form-group">
  <label class="col-md-4 control-label" for="period">Period:</label>  
  <div class="col-md-4">
  <input id="period" name="period" type="text" 
  placeholder="Period in days" class="form-control input-md" required="">

<!-- Text input-->

<div class="form-group">
  <label class="col-md-4 control-label" for="myIAT">Inter Arrival Time:</label>  
  <div class="col-md-4">
  <input id="myIAT" name="myIAT" type="text" 
  placeholder="Inter Arrival Time in Days." 
  class="form-control input-md" required="">

<!-- Button -->

<div class="form-group">
  <label class="col-md-4 control-label" for="submit"></label>
  <div class="col-md-4">
  <input type="submit" class="btn btn-info" value="Run Simulation">



Execute R Script in runr.php

Once your form is submitted, you will be redirected to the runr.php page, which will do four functions:

[a] It will empty the output folder from the results of the previous simulation.

$files = glob('output/*'); // glob() function searches for all the path names matching pattern
foreach($files as $file){ 
    unlink($file);         // delete

[b] It will get the values submitted by the HTML form and store it into variables to be passed as arguments required by R script

$nbeds = $_GET['nbeds'];   // number of beds / resources of the simulation
$myrep = $_GET['myrep'];   // number of simulation runs
$period = $_GET['period']; // period of the simulation run
$myIAT = $_GET['myIAT'];   // Interarrival time

[c] Execute R Script and pass arguments in the shell command:

// execute R script from shell

$output=shell_exec("Rscript /var/www/html/mycmd/myscript.R $nbeds $myrep $period $myIAT");
echo $output;

[d] Display output of the R script as image and as links to files in output folder:

echo "<img src='output/output.png'>";

$files = scandir('./output/');


foreach($files as $file){
   echo'<a href="output/'.$file.'">'.$file.'</a>';
echo '<br>';

Image 4


The above mentioned article contains the R script used to run the simulation in R studio. However, we need to fine tune the code if we are going to pass parameters and execute R script on Ubuntu server.

First, change the working directory:


Use commandArgs() function to scan arguments supplied when R script is called. The next step is to store arguments in variables.

args <- commandArgs(TRUE)
## Input Simulation parameters

nbeds<-as.integer(args[1])   ## number of beds
myrep<-as.integer(args[2])   ## number of repetitions
period<-as.integer(args[3])  ## run for two years 
myIAT<-as.numeric(args[4])   ## Inter Arrival Time (in Days) 

To export the chart into the desired folder that will be scanned by php to display on the web page, we will need to modify the R script as follows:

MyDataPlot<-grid.arrange(p1, p2, p3,p4, ncol=2)

png(filename="/var/www/html/mycmd/output/output.png", width = 800, height = 600)

The following command is added to export the console results as text file into the output folder to be later displayed as link on the web page:

sink('analysis-output.txt', append=FALSE, type = c("output", "message"))

Points of Interest

Installation of R on Ubuntu:

sudo apt-get update
sudo apt-get -y install r-base

Installation of simmer package:

> install.packages("simmer")

This command will install the dependencies as well. You will need to select the convenient mirror to download from. Furthermore, you will need to install more packages as it is needed in the R script to output the simulation charts.

> install.packages("ggplot2")
> install.packages("gridExtra")
> install.packages("dplyr")
> install.packages("tidyr")

These settings need a lot of optimization for best performance, we are illustrating a simple methodology to call R Script using a practical example. Beware of the "Resource Monster" especially if you are running the simulation with myrep >1000 .

Image 5



  • 25th August, 2016: Initial version
  • 3rd December, 2021: Article updated


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Team Leader
Egypt Egypt
Clinical Pharmacy AND Programming were, and still are, my life's passion. Children suffering from cancer has been my cause since 1998. I chose to "focus" on Children with Brain Tumors, as it is -till this day- one of the most challenging pediatric malignancies. Throughout my professional career, i learnt a lot of stuff to help me help children with cancer. Working with those under privileged kids also required me to have a deeper knowledge of Pediatric Oncology, Patient Education and cancer supportive care. I got training in different fields -not only- Clinical Pharmacy, but also Fundraising, Clinical Informatics and Web Development !

Comments and Discussions

QuestionIntegrate R with Laravel Pin
Member 1493980716-Sep-20 1:55
MemberMember 1493980716-Sep-20 1:55 
QuestionR script on php with input file Pin
Member 1461602617-Oct-19 3:50
MemberMember 1461602617-Oct-19 3:50 
QuestionR script on php with input file Pin
Member 1461602614-Oct-19 1:51
MemberMember 1461602614-Oct-19 1:51 
QuestionIntegrate R with PHP Pin
Anshul198624-May-18 23:07
MemberAnshul198624-May-18 23:07 
QuestionR Pin
Member 134493396-Oct-17 0:34
MemberMember 134493396-Oct-17 0:34 
AnswerRe: R Pin
MohamedKamalPharm15-Mar-18 2:05
MemberMohamedKamalPharm15-Mar-18 2:05 
QuestionDoubt working with windows Pin
Member 119702636-Dec-16 22:58
MemberMember 119702636-Dec-16 22:58 
AnswerRe: Doubt working with windows Pin
MohamedKamalPharm24-Jan-17 8:33
MemberMohamedKamalPharm24-Jan-17 8:33 
GeneralRe: Doubt working with windows Pin
ghousepasha27-Feb-18 12:30
Memberghousepasha27-Feb-18 12:30 
GeneralRe: Doubt working with windows Pin
MohamedKamalPharm15-Mar-18 2:11
MemberMohamedKamalPharm15-Mar-18 2:11 
GeneralRe: Doubt working with windows Pin
Member 1379182921-Apr-18 17:50
MemberMember 1379182921-Apr-18 17:50 
GeneralRe: Doubt working with windows Pin
MohamedKamalPharm15-Mar-18 2:13
MemberMohamedKamalPharm15-Mar-18 2:13 
GeneralRe: Doubt working with windows Pin
Member 1379182931-Aug-18 5:28
MemberMember 1379182931-Aug-18 5:28 
GeneralRe: Doubt working with windows Pin
Member 1379182931-Aug-18 7:03
MemberMember 1379182931-Aug-18 7:03 
GeneralRe: Doubt working with windows Pin
MohamedKamalPharm28-Sep-18 1:05
MemberMohamedKamalPharm28-Sep-18 1:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.