How to Integrate R with PHP

Deepanshu Bhalla 3 Comments

This tutorial explains how to integrate R with PHP.

Online reporting tools have gained popularity in recent years. There is a growing demand to implement advanced analytics in these tools. Use of advanced analytics help to solve various organization problems such as retaining existing customers or acquiring new customers etc.

PHP is one of the most popular programming language to develop websites and online reporting tools. It has rich functionality to write business logic, however they are not effective when it comes to data science and machine learning. In the field of data science, R dominates in terms of popularity among statisticians and data scientists with over 10k number of packages.

How to make PHP communicate with R

There are times when you want to showcase the output of R program like charts that you create based on the user inputted data from a web page. In that case you might want your PHP based web application to communicate with the R script.

When it comes to PHP, it has a very useful function called exec(). It lets you execute the outside program you provide as the source. We will be using the very same function to execute the R script you created. The then generates the graph and we will show the graph in our web page.

The exec function can be used on both the Linux and Windows environments.

  1. On the Linux environment it will open the terminal window to execute the command you set and arguments you specify.
  2. While on the Windows environment it will open the CMD to execute the command you provide along with the arguments you specify.

I will walk you through the process of integrating the R code with PHP web page with code and explanation. 

Let's first create a PHP based web form:
index.php:
<html>
  <head>
    <title>PHP and R Integration Sample</title>
  </head>
  <body>
    <div id=”r-output” id=”width: 100%; padding: 25px;”>
    <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
      exec("sample.R");
    ?>
    <img src=”test.png?var1.1” alt=”R Graph” />
    </div>
  </body>
</html>

Now save the file as index.php under your /htdocs/PROJECT-NAME/index.php.

Let’s create a sample chart using R code.

Write the following code and save it as sample.R file.

x <- rnorm(6,0,1)
png(filename="test.png", width=500, height=500)
hist(x, col="red")
dev.off()
Integrate R with PHP
Histogram

rnorm(6, 0 ,1) means generating 6 random values with mean 0 and standard deviation 1. The dev.off() command is used to close the graph. Once chart created it will save it as the test.png file.

The only downside of this code is that it will create the same test.png file for all the incoming requests. Meaning if you are creating charts based on user specified inputs, there will always be one test.png file created for various purpose.
Let’s understand the code

As specified earlier the exec('sample.R'); will execute the R script. It in turn generates the test.png graph image.

In the very next line we used the HTML <img /> tag to display the R program generated image on the page. We used the src=test.png?ver1.1 where ver1.1 is used to invalidate the browser cache and download the new image from server.

All modern browsers supports the browser caching. You might have experienced some website loads way faster on your repetitive visits. It’s due to the fact that browsers cache the image and other static resources for brief period of time.

How to serve concurrent requests?
sample2.R
args <- commandArgs(TRUE)
cols <- args[1]
fname <- args[2]
x <- rnorm(cols,0,1)
fname = paste(fname, "png", sep = ".")
png(filename=fname, width=500, height=500)
hist(x, col="red") dev.off()
Index.php
<html>
  <head>
    <title>PHP and R Integration Sample</title>
  </head>
  <body>
    <div id=”r-output” id=”width: 100%; padding: 25px;”>
    <?php
      // Execute the R script within PHP code
      // Generates output as test.png image.
      $filename = “samplefile”.rand(1,100);
      exec("sample2.R 6 “.$filename.");
    ?>
    <img src=”.$filename.”.png?var1.1” alt=”R Graph” />
    </div>
  </body>
</html>

It will help you eliminate the need to using the same test.png file name. I have used the $filename=”samplefile”. You can use any random sequence as I have used in the end of the samplefile name. rand(min, max) will help you generate a random number.

It will help you fix the file overwriting issue. And you will be able to handle the concurrent requests and server each with unique set of image(s).

You might need to take care of old file removals. If you are on a linux machine you can setup a cron job which will find and delete the chart image files those are older than 24 hours.

Here is the code to find and remove files:
Delete.php
<?php
// set the path to your chart image directory
$dir = "images/temp/";
// loop through all the chart png files inside the directory.
foreach (glob($dir."*.png") as $file) {
// if file is 24 hours old then delete it
if (filemtime($file) < time() - 86400) {
    unlink($file);
    }
}
?>
Conclusion

Making PHP communicate with R and showcase the result is very simple. You might need to understand the exec() function and some PHP code if in-case you want to delete those residual files/images generated by your R program.

Author Bio
This article was originally written by Darshan Joshi, later Deepanshu gave final touch to the post. Darshan is a programming enthusiast. He loves to help developers in every possible way. He is a founder of AlphansoTech : Web Application Development company. You can connect with him on LinkedIn.
Related Posts
Spread the Word!
Share
About Author:
Deepanshu Bhalla

Deepanshu founded ListenData with a simple objective - Make analytics easy to understand and follow. He has over 10 years of experience in data science. During his tenure, he worked with global clients in various domains like Banking, Insurance, Private Equity, Telecom and HR.

Post Comment 3 Responses to "How to Integrate R with PHP"
  1. thank you, it's been a very useful tutorial, i'm new in Data Science, and people like you make it look very simple and beautiful at the same time !

    ReplyDelete
  2. thank you
    but i have a question, if i want to using library R in PHP, what must i do?
    i want to using arulesSequences library and show the result to webpage

    thanks for attention

    ReplyDelete
  3. Hello. I have one question... When I want to show the summary of dataset in the body of html... It doesn't show... I am using this script in R
    library(datasets)
    datos <- function(){
    data(iris)
    print(summary(iris))
    }
    datos()
    How I can write the summary in the body with exec function on PHP ? THANKS !!!

    ReplyDelete
Next → ← Prev