Using rrdtool with PHP

The PHP interface to rrdtool hasn’t been updated in 5 years and appears to have been deprecated by the developer, who doesn’t provide any documentation for it. Fortunately, there’s no functionality in the extension, so it won’t go out of date as long as the rrdtool library on your system is up to date. I’ve managed to figure out the functions by looking at the source code and thought it might be helpful for someone.

/* Creates a graph based on options passed via an array */
mixed rrd_graph(string file, array args_arr, int argc);
 
/* Fetch info from an RRD file */
mixed rrd_fetch(string file, array args_arr, int p_argc);
 
/* Get the error message set by the last rrd tool function call */
string rrd_error(void);
 
/* Clear the error set by the last rrd tool function call */
void rrd_clear_error(void);
 
/* Update an RRD file with values specified */
int rrd_update(string file, string opt);
 
/* Gets last update time of an RRD file */
int rrd_last(string file);
 
/* Create an RRD file with the options passed (passed via array) */ 
int rrd_create(string file, array args_arr, int argc);
 
/* Dump an HTML page with info on rrdtool /*
string rrdtool_info(void);

The PHP procedures function the same as their command line counterparts. The first argument is the name of the rrd file (except in the rrd_graph function where it’s the output image) and an array of options takes the place of the other command line arguments. The following shell command and PHP excerpt both perform the same task.

rrdtool graph /tmp/my_graph.png \
--end=now \
--start=end-24h \
--title="I need quotes because of the spaces" \
DEF:/tmp/my_rrd_file:ds0 \
COMMENT:Escape a colon (\:) with a backslash
$opts = array(
	'--end', 'now',
	'--start=end-24h',
	'--title=I need no quotes because of the spaces',
	'DEF:/tmp/my_rrd_file:ds0',
	'COMMENT:Escape a colon (\\\\:) with four backslashes!'
);
$result = rrd_graph('/tmp/my_graph.png', $opts, count($opts));
if ($result === false) {
	echo 'There was an error: ';
	echo rrd_error();
}
else {
	echo 'File successfully created.';
}

Of course this isn’t functional, but it illustrates the relationship between the command line utility and the PHP interface. Note that the options can be specified as two separate array elements, as I did with the --end parameter, or as a single element, like --start. The functions rrd_create, rrd_update, rrd_fetch, and rrd_graph return false in case of an error; any detail must be retrieved using the rrd_error function.