OpenCPU – Using it with php

OpenCPU ( is a software which allow to use R to produce data (text, graph, etc) and serve them using a webserver (apache or nginx if you enable cache server). Another similar software is Shiny ( which use node.js. You must see what is the best solution for your needs 😉

I don’t now node.js, but I know apache and ph, so I choose OpenCPU: here are the steps to see it up and running. In this post I will show you the steps for using OpenCPU inside R session, but on his site you can find all the information to install it like a service.

Lets begin with the installation of some packages.

It is possible that you must change the version of libcurl, it depends on which version of curl you have installed.

Modify the configuration files of php to enable the new extension.

Restart apache to enable the new php function.

Now turn our focus on R. OpenCPU needs a new R package which exports the functions we need.

Create a new file and insert the following rows:

Save the file as “test_ocpu.R”.

Create the R package.

The previous command will create a new directory called “TestOcpu” which contains the files useful for package installation. You mut modify DESCRIPTION file (it is self explanatory) and NAMESPACE file. In the last file, insert the following rows:

This file allow us to publish the functions created, making it usable 🙂

If you want, compile files in man directory, otherwise remove them to avoid compilation errors.

Run the following command:

The package will be compiled and installed in you library directory.

Ok, lets begin.

Install and run OpenCPU. In a R session, run:

Here is the output:

The string after “[httpuv]” is the local server url. Copy it, we must use it in php file.

Create “opencpu.php” file with the following contents:

As value for “$server” variable, insert the row copied before.

Save and run from linux shell:

It will output teh result of quantile function and you will find a file named “graph.png” with the boxplot create from R 🙂

Posted in OpenCPU, PHP, Tutorial.