Example 2 -- PHP display the plot created by R

This page is for Linux only!!
  1. PHP code (ex_2.php)

        
    <?
    
      $cmd = "echo 'argv <- \"ex_2.r\"; source(argv)' | " .
             "/usr/bin/R --vanilla --slave";
    
      $handle = popen($cmd, "r");
      $ret = "";
      do{
        $data = fread($handle, 8192);
        if(strlen($data) == 0){
          break;
        }
        $ret .= $data;
      }
      while(true);
      pclose($handle);
    
      header("Content-type:image/png");
      echo $ret;
    
    ?>
    

    This PHP file use shell command echo pipe arguments to R and accept the return image from R and show it on web page.

  2. R script (ex_2.r)
    If the "ex_2.r" as the follows, it will return a rainbow pie chart.

        
      dev.off.wrap <- function(){
        dev.off()
        invisible()
      }
    
      bitmap(file = "%stdout", type="png256")
      pie(rep(1, 24), col = rainbow(24))
      dev.off.wrap()
    

    This R script just print the arguments.

  3. Browse
    Put the "ex_2.php" and "ex_2.r" into the same directory and open web browser to link "ex_2.php".
    Click here to see the pie chart from R script "ex_2.r".