Skip to content

Archive

Tag: PHP

PHP has a configuration settings in php.ini which allows you to specify the maximum file upload size.

The values we are interested in here are post_max_size which controls the largest size of a post allowed – which is important since files are uploaded to a server using a POST, and the upload_max_filesize parameter, which sets how an actual file can be to upload.

To find the maximum file size we can upload, we need to find the smallest of these two values.

We can get the config setting using the PHP function ini_get() but there is a catch to this. It returns the size in the format of something similar to 2M, so we need to parse this number so we can have the actual size in bytes as a number.

The code below is based on some code I found in the comments section on the php.ini page of the PHP manual.

	function convert_size_to_num($size)
	{
		//This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
		$l = substr($size, -1);
		$ret = substr($size, 0, -1);
		switch(strtoupper($l)){
		case 'P':
			$ret *= 1024;
		case 'T':
			$ret *= 1024;
		case 'G':
			$ret *= 1024;
		case 'M':
			$ret *= 1024;
		case 'K':
			$ret *= 1024;
			break;
		}
		return $ret;
	}

	function get_max_fileupload_size()
	{
		$max_upload_size = min(convert_size_to_num(ini_get('post_max_size')), $convert_size_to_num(ini_get('upload_max_filesize')));

		return $max_upload_size;
	}
Share

Now that we have everything in place, it would be nice to add a little bit of interactivity.

Since the script which generates the graph outputs an image, all we need to do put in place a few combo boxes so that we can select the values we want for the graph, and then all we do is call a Javascript function to change the inner html for the div containing the image with a new image referencing the updated url.

Now we can dynamically change our input values to get the data we want the graph to show.

Convert 

 to 

Period 
Convert  to 
Period 
Share

Now, that we can draw a graph of the exchange rate, the info contained within our database will quickly grow outdated if we do not update it with the new daily data.

Fortunately, the European Central Bank comes to the rescue once again. They have an XML feed which contains the latest exchange rate for all the currencies that are listed in the history data. All we need to do is get the contents and then extract the values we need out of it.

The XML feed can be found at http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml.

Using an XML parser, which converts the XML into an object, we can quickly find currencies we want, and then create an insert statement to update our database.

This script would need to be run daily to keep the database fully up-to-date, so one way to do this would be to run the script as a cron job on your server.

$row[ipaddress] = "localhost";
$row[dbusername] = "root";
$row[dbpassword] = "password";
$row[dbname] = "exchange";

$contents = '';
$file = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
if($handle = @fopen($file, "r")){
	while (!feof($handle)) {
	   $contents .= fread($handle, 8192);
	}
	fclose($handle);

	if (strlen($contents) > 0){

		$data = simplexml_load_string($contents);
		$currdate = (string)$currdate = $data->Cube->Cube['time'];
		foreach($data->Cube->Cube->Cube as $curr){
			switch ((string)$curr['currency']){
				case 'GBP':
					$gbp = (string)$curr['rate'];
					break;
				case 'USD':
					$usd = (string)$curr['rate'];
					break;
				case 'ZAR':
					$zar = (string)$curr['rate'];
					break;
				case 'NZD':
					$nzd = (string)$curr['rate'];
					break;
				case 'AUD':
						$aud = (string)$curr['rate'];
				case 'CHF':
						$chf = (string)$curr['rate'];
					break;
			}
		}		
		$dbconn = mysql_connect($row[ipaddress], $row[dbusername], $row[dbpassword]);
		mysql_select_db($row[dbname], $dbconn);
		echo $gbp;

		$sql = "SELECT * FROM `exchangerates` WHERE `ratedate` = '$currdate'";
		$res = mysql_query($sql, $dbconn);
		if (mysql_num_rows($res) == 0){
			$sql = "INSERT INTO `exchangerates` (`ratedate`, `GBP`, `USD`, `ZAR`, `AUD`, `NZD`, `CHF`) VALUES ('$currdate', '$gbp', '$usd', '$zar', '$aud', '$nzd', '$chf')";
			echo $sql;
			mysql_query($sql, $dbconn);
		}
		mysql_close($dbconn);
	}
}

In the next part of the series, we will be putting the finishing touches on creating the graph

Share

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.

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>
continue reading…

Share

Over the next few blog posts I am going to explain how to create an exchange rate graphing script in PHP, which takes the two currencies as input as well as the period to calculate for, and then outputs an image showing the graph of how the exchange rate has varied over time.

One of the biggest problems when trying to display exchange rate data is where to get the data to display, but that is not a major worry, as there are several sources of this information freely available on the web.

The source where I got the historical data is from the European Central Bank, which publishes a list of exchange rates for many currencies against the Euro, with historical data dating back to 1999. The data is available for download here.

Of particular note here is the historical file, which can be downloaded as a CSV, which we are going to use to populate our database.

The first thing we need to do though is to create a MySQL database to store the exchange rate data in. The query to create the table we need is as follows:

CREATE TABLE `exchangerates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ratedate` date DEFAULT NULL,
  `GBP` decimal(10,4) DEFAULT NULL,
  `USD` decimal(10,4) DEFAULT NULL,
  `ZAR` decimal(10,4) DEFAULT NULL,
  `AUD` decimal(10,4) DEFAULT NULL,
  `NZD` decimal(10,4) DEFAULT NULL,
  `CHF` decimal(10,4) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

Now that we have a database structure and have the historical exchange rate data, we need a script to populate our database. This is done with this little script.

what this script does is parse the CSV file, and then selects the columns in the CSV corresponding to the currencies we are interested in – we don’t want most of the currencies. The script builds an insert statement for each line and then executes the query against the database, and at the end of it, we have the full historical exchange rate data since 1999 in our database.
continue reading…

Share

Most PHP programmers have to deal with Javascript in some form or another. It is a rare project that solely uses PHP to the exclusion of Javascript.

To help out PHP programmers, and at the same time, add some useful functionality to Javascript, there is a project called php.js.

What this open source project has done, is write a library of functions in Javascript that mirror the functionality available within PHP. This means you get things like md5(), strip_tags(), strtotime().

The project is not trying to create a PHP emulator in Javascript, but rather to provide the functions available in PHP in Javascript, which means a programmer well-versed in PHP will be much more productive in Javascript.

Share

Titanium 0.7 has just been released, and some of the features do look rather exciting.

By far, the best new feature is PHP support, which adds a whole new dimension to Titanium development. It will also facilitate the porting of existing codebases and frameworks to Titanium apps, potentially increasing the market substantially.

Another great new feature is the introduction of native social APIs. You will be able to connect to Yahoo YQL, Facebook Connect and Twitter all from directly in a Titanium application.

There are a quite a few smaller changes, and while I have yet to confirm it, I have it on good authority that Titanium 0.7 also now supports native drag and drop functionality.

Things are really looking good and Titanium seems to be maturing nicely.

Share