szpal szpal - 7 months ago 15
PHP Question

Realtime image from rrd file in PHP

I would like to generate a "realtime" image from a rrd file in php script, but no success.
This is the php script (/var/www/rrd_image.php), which should generate the picture:

<?php
header("Content-type: image/png");

$options = array(
"--start", "-1d",
"--title=xxx",
"--lower-limit=0",
"--width=450",
"--height=120",
"DEF:snr=/var/www/rrd/cm_100.rrd:snr:LAST",
"CDEF:tsnr=snr,10,/",
"LINE:tsnr#00FF00:US SNR",
"GPRINT:tsnr:MIN:Min\: %3.1lf dB",
"GPRINT:tsnr:MAX:Max\: %3.1lf dB",
"GPRINT:tsnr:LAST:Pill\: %3.1lf dB",
);

rrd_graph("-", $options);
?>


So I'm calling it like this:

<img src="rrd_image.php" />


But the picture is not completed, in the browser i see, that it is 0 bytes, and there is no error in apache log.
(And when i run a rrd_image.php from console, then it works, the "image" goes to the standard output.)

Answer

You do this wrong, because rrd_graph() returns array not image. You should change this to look it i.e. like this:

$fileName = "rrd.png";
rrd_graph($fileName, $options);

header("Content-Type: image/png");
header("Content-Length: " . filesize($name));

$fp = fopen($name, 'rb');
if( $fp ) {
  fpassthru($fp);
  fclose($fp);
}

exit();

Please always read the docs first: http://php.net/manual/en/function.rrd-graph.php

PS: Unless you know you need it, never use ?> - it saves you from accidentally outputing something back to i.e. browser (like whitespaces or LFs after the ?>)