Interactively generate and embed a picture in PhP

I have been building a website with one of my MSc students. One of the things we want to do is to take a value from the user, process some information based on it and visually display the output.

The solution is simple but took us a couple of days to figure out. So here a simple illustrative example for anyone else facing similar problems. You will need two scripts – the first to take the user input and call the second script which plots it. The important thing about the second script is that it must return a plot and nothing else (no text etc).

Here is an example of the first script (the calling script). This script calls the second script using the query strings option.


<html>

<?php

if( empty($_POST['val']) ){                // first time user
  $message = "Welcome first timer. Please enter a value to add to the plot:";

} else {

  $val=$_POST['val'];
  echo "You entered a value of ". $val. " and here is your requested plot<br><br>";
  echo '<img src="make_plot.php?passingValue=' . $val . ' " width=800 />';
  echo "<br>Hope you enjoyed it. Bye!<br><hr><br>";

  $message = "Enter another value to re-plot:";
}
?>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
   <?php echo $message; ?> <br>
   <input type="text" name="val"><br>
</form>

</html>

And here is an example of the second script (the called script) which is named make_plot.php. This script uses the GET method since it’s called using query strings.

<?php 
define("PCHART_PATH", "/home/web/pChart/"); include(PCHART_PATH."class/pDraw.class.php"); include(PCHART_PATH."class/pImage.class.php"); include(PCHART_PATH."class/pData.class.php"); $receivedValue=$_GET["passingValue"]; $myData = new pData(); $myData--->addPoints( array(1,5,3,7,5,9,7,10,$receivedValue) );

$myPicture = new pImage(700,230,$myData);
$myPicture->setFontProperties(array("FontName" => PCHART_PATH . "/fonts/GeosansLight.ttf", "FontSize" => 11));
$myPicture->setGraphArea(60,40,670,190);
$myPicture->drawScale();
$myPicture->drawSplineChart();

$myPicture->Stroke();
?>

Here, we are using the pChart package for drawing. In real life this script is more complicated with computing done based on the $receivedValue parameter.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s