The United Kingdom postcode database is owned by the Royal Mail, who charge high fees for licences. Resellers such as Postcode Anywhere provide pay-as-you-go access, but even this in an unnecessary expense if only basic validation is required. Postcode is a PHP class that can validate postcode formats, extract parts of postcodes, and determine the post towns corresponding to postcodes.
Download Postcode
Download the two files below and upload them to your web server. The database is only required for the getPostTown function. You should periodically update your copy of the database to the latest version.
File | Size | Description |
---|---|---|
class.Postcode.php | 5,479 bytes | PHP class |
Postcode.data | 77,740 bytes | Database (updated May 2014) |
Validating a postcode
Postcode can validate that a string is in the general format of a UK postcode through the isValidFormat function:
1 2 3 4 5 6 7 8 9 |
|
Note that this function only validates the format of a postcode and does not validate that the postcode exists; this would require access to the Royal Mail database. This function allows the characters in the postcode to be in either upper or lower case, and permits any amount of leading and trailing space and space between the first and second parts. To convert the postcode to a standard format, use the getUnit function described below.
Accessing the parts of a postcode
A postcode consists of various parts, from the area (the initial letters, corresponding to 121 divisions of the UK) to the unit (the entire postcode). The getArea, getDistrict, getSector, and getUnit functions can be used to access these parts. These functions return the parts in a normalised format, so getUnit can be used to convert a postcode to a standardised format. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
These functions return false if passed a string that is not in a valid postcode format.
Determining post towns
While a postcode and property number is usually sufficient information to uniquely identify a property, items are more likely to be delivered correctly and on time if the full address and post town are supplied. The getPostTown function determines the post town (in upper case, as the Royal Mail recommend) for a postcode:
1 2 3 4 5 |
|
This function returns false if passed a string that is not in a valid postcode format. If the postcode district could not be found in the database this function returns an empty string; this may mean that the postcode does not exist, or it may mean that your copy of the database is not up-to-date.