Friday, December 29, 2006

Zip Code To Location Validation

Jason Palmer has a function which make sure the zip code entered by user matches the city and state upon verification function return true, otherwise false. Here goes the post from him..

Recently, a client was interested in verifying that any inputted zip code was matched correctly with the city and state the user provided. This can be a very valuable and important thing to verify, especially if you are shipping items.

Using the CodeBump GeoPlaces Web Service I constructed a function which takes three parameters (zip, city, state) and does a case-insensitive comparison to make sure that the given zip code matches the city and state. Upon verification the function will return true. Otherwise, it returns false.

The GeoPlaces Web Service requires a paid membership. Once you receive a subscription, CodeBump will send you a valid subscriptionID and that is the only thing you will have to provide for this function to work correctly.

<?PHP
//Written by Jason Palmer, 2006.
//Use as you please just please reference back to:
//http://www.jason-palmer.com/

//Returns true on success, and false on failure.
function zip_2_loc($zip, $city, $state)
{
//Provide your subscriptionID
$subscriptionID = ‘;

//Construct the URL
$url = "http://codebump.com/services/placelookup.asmx/
GetPlacesInside
";
$url .= "?AuthenticationHeader=" . $subscriptionID;
$url .= "&place=" . $zip . "&state=";

//Open the URL and read contents
$contents = fopen($url, "r");
$data = fread($contents, 8192);

//Convert XML data to array
$xml = new SimpleXMLElement($data);

foreach($xml->GeoPlaceDistance as $key => $value)
{
//Match case insensitive
if(strtolower($city) == strtolower($value->ToPlace)
&& strtolower($state) == strtolower($value->ToState))
{
//Match
return true;
}
}
return false;
}
?>

No comments: