HOW TO INTEGRATE R WITH PHP : php와 R 언어의 연동

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, increasing customer satisfaction 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()
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.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

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 Twitter and LinkedIn.
[출처] https://www.listendata.com/2017/04/how-to-integrate-r-with-php.html
본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
128 Creating a Website Design Templating System Using PHP 졸리운_곰 2021.02.13 22
127 Build a CRUD Operation using PHP & MongoBD 졸리운_곰 2021.01.04 23
126 CRUD Operation using PHP & Mongodb file 졸리운_곰 2021.01.04 26
125 PHP and MongoDB Connection file 졸리운_곰 2021.01.04 62
124 PHP 기반의 Micro Frameworks 정리 졸리운_곰 2020.12.02 50
123 CKEditor 4 설치와 PHP 연동 하기 file 졸리운_곰 2020.11.22 47
122 [php] CKeditor 설정 및 적용 졸리운_곰 2020.11.22 37
121 [PHP]Fuelframework 설치 및 시작 방법(window10,xampp) file 졸리운_곰 2020.10.01 34
120 Building a Simple Blog App with MongoDB and PHP file 졸리운_곰 2020.09.13 50
119 웹 설문조사 시스템 & 설문조사를 잘 하는 방법 file 졸리운_곰 2020.09.10 185
118 ReactPHP Series 졸리운_곰 2020.07.01 50
117 Building a RESTful API Using ReactPHP and MySQL file 졸리운_곰 2020.07.01 44
116 [PHP 웹개발] MySQL 데이터베이스에서 mysqli(MySQL Improved) 사용법 졸리운_곰 2020.05.07 37
115 PHP 파일 업로드와 다운로드 만들기 file 졸리운_곰 2020.05.07 372
» HOW TO INTEGRATE R WITH PHP : php와 R 언어의 연동 file 졸리운_곰 2020.05.05 243
113 XAMPP, PhpStorm, Hello World 출력하기 졸리운_곰 2020.03.27 40
112 Pico is a stupidly simple, blazing fast, flat file CMS. file 졸리운_곰 2020.03.19 30
111 directorylister php 사용법 file 졸리운_곰 2020.03.18 129
110 flat file 플랫파일시스템 : GRAV CMS file 졸리운_곰 2020.03.18 60
109 내가 본 워드프레스 핵심 구조 및 기능 (Wordpress Architecture and Function) file 졸리운_곰 2020.02.20 34
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED