Australian Postcode Validation using the AusPost website

posted in: Development, PHP | 0

I’m currently working on an ecommerce site that needs strong validation of post code and address, so that the Australia Post postage costs can be accurately calculated and passed on to the customer.

One interesting method to do this can be to use the auto completion “app” on the AusPost website. For Example the following url lists all areas in the 2345 postcode http://auspost.com.au/apps/postcode-autocomplete.html?q=2345&limit=20

However this web “app” is ultimately not 100% reliable, because it designed to be used in conjunction with the AusPost website, and because AusPost may remove this page at any time or change its mode of operation or format of its results.

A better solution for business applications is to use the CSV data, which is available for free download from AusPost here

In my next posting I’ll publish the process of creating a MySQL database table from the CSV data and performing searches on this data using PHP.

But as a purely technical exercise in interfacing to this “app”, I’m publishing my php code below.

<?php
 
	// Validate Australian postcode using the AutoComplete app on auspost.com.au
	public function validate_postcode_online($postcode,$city=null,$stateCode=null) 
	{
		// Build respose to query into array of arrays
		$response = split("[\n]",trim(file_get_contents("http://auspost.com.au/apps/postcode-autocomplete.html?q=".$postcode."&limit=20")));
		$arr=array();
		foreach($response as $entry)
		{
			array_push($arr,split("[|]",trim($entry)));
		}
 
		if ($arr[0][1]!=$postcode)
		{
			return false;//"Invalid postcode";// postcode does not exist
		}
 
		if ($city!==null)
		{
			$foundCity=false;
			$city = strtoupper($city);
			// check city against all items in list
			foreach($arr as $entry)
			{
				if ($entry[2]==$city)
				{
					$foundCity=true;
					break;
				}
			}
			if ($foundCity==false)
			{
				return false;//"Postcode does not match the city";
			}
		}
 
		if ($stateCode!==null)
		{
			$foundState=false;
			$stateCode = strtoupper($stateCode);
			foreach($arr as $entry)
			{
				if ($entry[3]==$stateCode)
				{
					$foundState=true;
					break;
				}
			}
			if ($foundState==false)
			{
				return false;//"Postcode does not match State";
			}
		}
 
		return true;//"ALL OK"; // All information is correct		
 
}

Here is an exmple of how to call the function

<?php 
	$postcode = "3000";// 
	$city="Melbourne";
	$stateCode="Vic";
 
	$start = microtime(true);
	echo '<html><body>';
	echo validate_postcode_online($postcode,$city,$stateCode);
 
	$end = microtime(true);
	echo '<br/>In '. ($end - $start).' secs';
	echo '</body><html>';
?>