#native_company# #native_desc#
#native_cta#

City/State lookup for zip codes via USPS web cgi

By David Webb
on October 4, 2001

Version: 0.2

Type: Full Script

Category: Other

License: GNU General Public License

Description: This script looks up a city and state for a given zip code from the USPS web cgi
for the same task. I made it for a shopping cart shipping information form
where we determine the city and state by a user selection from a list of valid
cities and states for their zip code. I decided to post it here because I am angry
that there are no publicly available free zip code databases. One would think it should be public record. This script simply posts a fake browser POST to USPS’ web cgi for looking up zip codes and formats the data returned into nice variables and prints out the results in a table. Hopefully this will save someone out there the time and money involved in the purchase of a zip code database. I wrote this script August 1st 2001, and as long as the USPS haven’t changed their zip code lookup cgi this script will work fine for you. Simply post a ‘shipZip’ field to this script, and you will be returned a table of valid cities and states for that zip code courtesy of USPS.

<table border='1'>
 <tr><td colspan=4><center><b><?php print $shipZip; ?></b></center></td></tr>
 <tr bgcolor=#D5DDFF>
  <td>City</td>
  <td>State</td>
 </tr>
<?php

$poststring="POST /cgi-bin/zip4/ctystzip2 HTTP/1.0n".
            "From: [email protected]".
            "User-Agent: Internet Explorer 5.0/1.0n".
            "Content-Type: application/x-www-form-urlencodedn".
            "Content-Length: 21nn".
            "FormsEditField1=$shipZipn";

$fp = fsockopen("www.usps.gov", 80, $errno, $errstr, 30);
if (!$fp) { echo "$errstr ($errno)<br>n"; } else {
    
  fputs($fp, $poststring);
  $buffer="";
  while (!feof($fp)) { $buffer="$buffer".fgets($fp,128); }
  fclose ($fp);

  $bufferarray = explode("n",$buffer);
  $i=0;
  while($i <= count($bufferarray)) {
    if(strstr($bufferarray[$i],"ACCEPTABLE")) { $resultstring=$bufferarray[$i]; }
    $i++; }

$resultarray = spliti("<br>",$resultstring);
  $i=0;
  while($resultarray[$i]) {
    if($i >= 3) {
      if(!strstr($resultarray[$i],"NOT ACCEPTABLE") && strstr($resultarray[$i],"ACCEPTABLE")) {

      	$j  = trim(substr($resultarray[$i], 0, strpos($resultarray[$i],"ACCEPTABLE")));     	
      	$k  = strrpos($j," ");
        $cityname    = trim(substr($j, 0, $k));
        $statestring = trim(substr($j,    $k));
        $statename   = $statestring[0].$statestring[1];      // Why did you do this????
        
        if(($i % 2) == 0) { $rowattr = "bgcolor=#EEEEEE"; } else { $rowattr = ""; }
        print "<tr $rowattr>n";
        print " <td>$cityname</td>";
        print " <td>$statename</td>";
        print "</tr>"; } }
    $i++; } }
?>      
</table></body></html>