Now that we have the basics in place for creating an exchange rate graph from the last part, we can now use the data we have captured to draw a graph. mybloggingplanet.com/2015/09/link-building-guide.html

We pass to the script the parameters fromcurr, which is the currency to convert from, tocurr, which is the currency to convert to, the valid values being, ZAR, GBP, USD, AUD, NZD and CHF. The last parameter is period which can be month, 6month, year, 5year and 10year.

The first thing we do is process the parameters we have been passed to find out the currencies and periods we need, which we then use to get the exchange rate data for the values we are looking for.
We then calculate the conversion rate for each row in the data we have returned, which will be used to draw the graph.

To draw the graph itself, we use the imagecreate() function to create an image, and then use the inbuilt php image drawing functions to draw the data onto the image we have created.

Essentially all we need to do is iterate though our conversion rates and draw the data point on the graph at the relevant location by applying a scaling factor to the value which will put the values within the pixel range which we desire.

At this point we also draw all necessary labels and guidelines for the chart.

Once we finish drawing the graph, we call imagepng() which causes the script to output the image data directly. We can then call this script from within an <img> tag, for example
<img src=”www.someserver.com/exchangegraph.php?tocurr=GBP&fromcurr=ZAR&period=5year>

require_once('csvparser.php');

class general{
	
	public static function getParam($param, $default = null){
		if (isset($_POST[$param]))
		{
			return $_POST[$param];
		}
		elseif (isset($_GET[$param]))
		{
			return $_GET[$param];
		}
		else
		{
			return $default;
		}
	}
	
    public static function getCookie($value, $default = null)
    {
        if (isset($HTTP_COOKIE_VARS[$value]))
        {
            $result = $HTTP_COOKIE_VARS[$value];
        }
        else
        {
            $result = $default;
        }

        return $result;
    }
    	
	public static function simpleRandString($length = 20, $list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
	{
		mt_srand((double)microtime()*1000000);
		$newstring="";
		while(strlen($newstring) < $length)
		{
			$newstring.=$list[mt_rand(0, strlen($list)-1)];
		}
		return $newstring;
	}
	
	public static function redirect($url)
	{
		header("Location: ".$url);
	}

}

function getSymbol($curr)
{
	switch($curr){
		case 'EUR':
			return 'E';
			break;
		case 'USD':
			return 'US$';
			break;
		case 'GBP':
			return '£';
			break;
		case 'NZD':
			return 'NZ$';
			break;
		case 'ZAR':
			return 'ZAR';
			break;
		case 'AUD':
			return 'AU$';
			break;
		case 'CHF':
			return 'CHF';
			break;
	}	
}
function getCurrencyData($currlist, $startdate, $enddate)
{
	$dbconn = mysql_connect("localhost", "root", "password");
	mysql_select_db("exchange", $dbconn);
	
	$collist = "";
	foreach($currlist as $curr){
		$collist .= ", `$curr`";
	} 
	
	$currData = array();
	$sql = "SELECT `ratedate`$collist FROM `exchangerates` WHERE `ratedate` >= '$startdate' AND `ratedate` <= '$enddate' ORDER BY `ratedate`";
	if ($result = mysql_query($sql, $dbconn)){
		while ($row = mysql_fetch_assoc($result)){
			$currData[] = $row;
		}
			
	}
	mysql_close($dbconn);
	return $currData;
} 

function getConvRate($fromCurr, $toCurr, $data)
{
	if ($fromCurr == 'EUR'){
		$fromRate = '1';
	}else{
		$fromRate = $data[$fromCurr];
	}
	if ($toCurr == 'EUR'){
		$toRate = '1';
	}else{
		$toRate = $data[$toCurr];
	}
	$rate = $fromRate / $toRate;
	return round($rate, 4);
		
}

$fromCurr = general::getParam('fromcurr', 'ZAR');
$toCurr = general::getParam('tocurr', 'GBP');
$timePeriod = general::getParam('period', 'year');
$currList = array();
if ($fromCurr != 'EUR'){
	$currList[] = $fromCurr;
}
if ($toCurr != 'EUR'){
	$currList[] = $toCurr;
}
$enddate = date("Y-m-d");
switch ($timePeriod){
	case 'month':
		$startdate = date("Y-m-d", mktime(0, 0, 0, date("m")-1, date("d"), date("Y")));
		break;
	case '6month':
		$startdate = date("Y-m-d", mktime(0, 0, 0, date("m")-6, date("d"), date("Y")));
		break;
	case 'year':
		$startdate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")-1));
		break;
	case '5year':
		$startdate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")-5));
		break;
	case '10year':
		$startdate = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d"), date("Y")-10));
		break;
}
$currData = getCurrencyData($currList, $startdate, $enddate); 

$rate = array();
for ($i = 0; $i < count($currData); $i++){
	$rate[] = getConvRate($fromCurr, $toCurr, $currData[$i]);
}


header("Content-type: image/png");
$graphLeft = 25;
$graphWidth = 370;
$graphTop = 20;
$graphHeight = 160;
$imageWidth = 400;
$imageHeight = 250;

$im = imagecreate($imageWidth, $imageHeight);
$backCol = imagecolorallocate($im, 255, 255, 255);
$lineCol = imagecolorallocate($im, 140, 140, 140);
$graphCol = imagecolorallocate($im, 0, 0, 255);
$textCol = imagecolorallocate($im, 0, 0, 0);

$maxY = max($rate);
$minY = min($rate);
$scaleY = ($maxY - $minY) / $graphHeight;
$scaleX = count($rate) / $graphWidth;
$prevX = $graphLeft;
$prevY = $graphHeight + $graphTop - round((($rate[0] - $minY) / $scaleY), 0);
imagefill($im, 10, 10, $backCol);
imagerectangle($im, $graphLeft, $graphTop, $graphLeft + $graphWidth, $graphTop + $graphHeight, $lineCol);
for($i = 1; $i < 5; $i ++){
	$lineY = $graphTop + round(($graphHeight  * ($i / 5)), 0);
	$val = round($maxY - (($graphHeight  * ($i / 5)) * $scaleY), 2);
	imageline($im, $graphLeft, $lineY, $graphLeft + $graphWidth, $lineY, $lineCol);
	imagestring($im, 1, 0, $lineY - 4, $val , $textCol);
}
imagestring($im, 1, 0, $graphTop - 4, round($maxY, 2) , $textCol);
imagestring($im, 1, 0, $graphTop + $graphHeight - 4, round($minY, 2) , $textCol);
$lbl = getSymbol($fromCurr)."/".getSymbol($toCurr);
imagestring($im, 3, round($imageWidth / 2, 0) - 30, 0, $lbl , $textCol);

$labelX = $graphLeft;
imagestringup($im, 1, $labelX - 4, $graphTop + $graphHeight + 55, $currData[0]['ratedate'] , $textCol);
imageline($im, $labelX, $graphTop + $graphHeight, $labelX, $graphTop + $graphHeight + 5, $lineCol);
for($i = 0; $i < count($rate); $i++){
	$x = round(($i / $scaleX), 0) + $graphLeft;
	$y = $graphHeight + $graphTop - round((($rate[$i] - $minY) / $scaleY), 0);
	imageline($im, $prevX, $prevY, $x, $y, $graphCol);
	if ($x >= $labelX + 20){
		$labelX = $x;
		imagestringup($im, 1, $labelX - 4, $graphTop + $graphHeight + 55, $currData[$i]['ratedate'] , $textCol);
		imageline($im, $labelX, $graphTop + $graphHeight, $labelX, $graphTop + $graphHeight + 5, $lineCol);
	}
	$prevX = $x;
	$prevY = $y;

}
imagepng($im);
imagedestroy($im);

In the next part, I will show you how to keep the exchange rate data up to date.

Share