PHP

Hi does any one know how i can validate if address is real by php. I need only US address
LVL 1
umaximAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ray PaseurCommented:
And here is a teaching example of how to use the GEOIO service.  As you can see, it returns the country in its response string.

HTH, ~Ray
<?php // RAY_geoio_curl_example.php
error_reporting(E_ALL);


// GET INFORMATION ABOUT YOUR SITE VISITORS' LOCATION FROM GEOIO.COM
// THE ACCURACY OF THIS SERVICE IS VERY GOOD - OFTEN WITHIN ONE KILOMETER
// MAN PAGE: http://www.iana.org/numbers/
// MAN PAGE: http://www.geoio.com/


// CONSTRUCT THE QUERY STRING FOR THE WEB SERVICE WITH THE CLIENT IP ADDRESS
$args["q"]   = isset($_SERVER["REMOTE_ADDR"]) ? $_SERVER["REMOTE_ADDR"] : NULL;
$args["qt"]  = 'geoip';
$args["d"]   = 'pipe';

// GET YOUR API KEY FROM http://www.geoio.com/signup.php
$args["key"] = 'YOUR KEY HERE';

// THIS IS THE URL FOR THE API
$url = "http://api.geoio.com/q.php";

// CALL THE API - MAY NEED BETTER ERROR HANDLER?
$dat = my_curl($url, $args);
if (!$dat) die("CALL TO $url FAILED");

// THE API RETURNS A PIPE-DELIMITED STRING OF INFORMATION
$inf = explode('|', $dat);

// SHOW WHAT WE GOT
echo "<pre>";
echo PHP_EOL . "CITY:    $inf[0] ";
echo PHP_EOL . "STATE:   $inf[1] ";
echo PHP_EOL . "COUNTRY: $inf[2] ";
echo PHP_EOL . "CARRIER: $inf[3] ";
echo PHP_EOL . "LAT:     $inf[4] ";
echo PHP_EOL . "LON:     $inf[5] ";
echo PHP_EOL;

// PREPARE A GOOGLE MAP LINK USING THE GEOLOCATION INFORMATION
$lnk = "<a target='_blank' href='http://maps.google.com/maps?f=q&source=s_q&hl=en&q=$inf[4],$inf[5]'>MAP: $inf[4],$inf[5]</a>";
echo PHP_EOL . $lnk;
exit;


// A FUNCTION TO RUN A CURL-GET CLIENT CALL TO A FOREIGN SERVER
function my_curl
( $url
, $get_array=array()
, $timeout=3
, $error_report=TRUE
)
{
    // PREPARE THE ARGUMENT STRING IF NEEDED
    $get_string = '';
    foreach ($get_array as $key => $val)
    {
        $get_string .= urlencode($key) . '=' . urlencode($val) . '&';
    }
    $get_string = rtrim($get_string, '&');
    if (!empty($get_string)) $url .= '?' . $get_string;

    $curl = curl_init();

    // HEADERS AND OPTIONS APPEAR TO BE A FIREFOX BROWSER REFERRED BY GOOGLE
    $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
    $header[] = "Cache-Control: max-age=0";
    $header[] = "Connection: keep-alive";
    $header[] = "Keep-Alive: 300";
    $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
    $header[] = "Accept-Language: en-us,en;q=0.5";
    $header[] = "Pragma: "; // BROWSERS USUALLY LEAVE BLANK

    // SET THE CURL OPTIONS - SEE http://php.net/manual/en/function.curl-setopt.php
    curl_setopt( $curl, CURLOPT_URL,            $url  );
    curl_setopt( $curl, CURLOPT_HTTPHEADER,     $header  );
    curl_setopt( $curl, CURLOPT_TIMEOUT,        $timeout  );
    curl_setopt( $curl, CURLOPT_USERAGENT,      'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'  );
    curl_setopt( $curl, CURLOPT_REFERER,        'http://www.google.com'  );
    curl_setopt( $curl, CURLOPT_ENCODING,       'gzip,deflate'  );
    curl_setopt( $curl, CURLOPT_AUTOREFERER,    TRUE  );
    curl_setopt( $curl, CURLOPT_RETURNTRANSFER, TRUE  );
    curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, TRUE  );

    // RUN THE CURL REQUEST AND GET THE RESULTS
    $htm = curl_exec($curl);

    // ON FAILURE HANDLE ERROR MESSAGE
    if ($htm === FALSE)
    {
        if ($error_report)
        {
            $err = curl_errno($curl);
            $inf = curl_getinfo($curl);
            echo "CURL FAIL: $url TIMEOUT=$timeout, CURL_ERRNO=$err";
            var_dump($inf);
        }
        curl_close($curl);
        return FALSE;
    }

    // ON SUCCESS RETURN XML / HTML STRING
    curl_close($curl);
    return $htm;
}

Open in new window

0
umaximAuthor Commented:
No you do not understand i need some script for example if i put 104-05 metropolitan new york it check if this address is real. Like many website do if you put some fake address they said we can not found your address
0
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Ray PaseurCommented:
OK, I understand that you want a street address instead of an IP address.  You can call the Google or Yahoo geocoder to see if they can return the geolocation of the address.  Try this link (there is no shithole lane in McLean).
http://www.laprbass.com/RAY_class_SimpleGeoCoder.php?a=614+shithole+lane&c=McLean&s=VA&z=22101&_go=go

Next try this link:
http://www.laprbass.com/RAY_class_SimpleGeoCoder.php?a=1448+colleen+lane&c=McLean&s=VA&z=22101&_go=go

From the different outputs you can see that the geocoders have some knowledge of what is a valid address.  HTH, ~Ray
<?php // RAY_class_SimpleGeoCoder.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;


// API KEYS, ETC., IF REQUIRED
// require_once('local_data.php');


// A FREEFORM NAMED LOCATION STATEMENT IS OPTIONAL - PROCESSED FIRST
if (!empty($_GET["n"]))
{
    $location = trim($_GET["n"]);
}
// ADDRESS, CITY, STATE, ZIP ARE OPTIONAL - PROCESSED IF FREEFORM LOCATION IS NOT PRESENT
else
{
    $location = '';
    if (!empty($_GET["a"])) { $location .= $_GET["a"] . ' '; }
    if (!empty($_GET["c"])) { $location .= $_GET["c"] . ' '; }
    if (!empty($_GET["s"])) { $location .= $_GET["s"] . ' '; }
    if (!empty($_GET["z"])) { $location .= $_GET["z"] . ' '; }
    $location = trim($location);
}

// IF WE HAVE A LOCATION STRING, RUN THE GEOCODERS
if ($location)
{
    // PREPARE THE SIMPLE GEO-CODER
    $demo = new SGC;

    // TEST THE YAHOO! GEOCODER
    $demo->YGC($location);
    echo PHP_EOL . "YAHOO! ";
    print_rr($demo);

    // TEST THE GOOGLE GEOCODER
    $demo->GGC($location);
    echo PHP_EOL . "GOOGLE ";
    print_rr($demo);
}
// ALL DONE PROCESSING THE INPUT, PUT UP THE FORM
?>
<html>
<head>
<title>Yahoo/Google SimpleGeoCoder Demo</title>
</head>
<body>
<form method="get">
Try using a full or partial address.
Addr: <input type="text" name="a" autocomplete="off" />
City: <input type="text" name="c" autocomplete="off" />
ST:   <input type="text" name="s" autocomplete="off" size="2" />
Zip:  <input type="text" name="z" autocomplete="off" size="8" />
<input type="submit" value="GeoCode This Address" />

Or use the name of a location.
Name: <input type="text" name="n" autocomplete="off" />
<input type="submit" value="GeoCode This Location Name" />
</form>
</body>
</html>

<?php
// SIMPLE GEOCODER CLASS
class SGC
{
    // DECLARE THE WORKING DATA
    private $precis;

    // DECLARE THE OUTPUT DATA
    public $latitude;
    public $longitude;
    public $precision;
    public $warning;
    public $error;
    public $geocoder;

    // DECLARE THE CONSTRUCTOR
    public function __construct()
    {
        $this->latitude  = 0.0;
        $this->longitude = 0.0;
        $this->precision = FALSE;  // WANT A VALUE OF 5 OR HIGHER, HIGHER IS BETTER, 8 IS ON THE ROOFTOP
        $this->warning   = '';
        $this->geocoder  = '';
        $this->error     = '';
        unset($this->precis);
    }

    // DECLARE THE DATA-CLEANUP
    private function _cleanup($str)
    {
        $str = preg_replace('/[^\' a-zA-Z0-9&!#$%()"+:?\/@,_\.\-]/', '', $str);
        return trim(preg_replace('/\s\s+/', ' ', $str));
    }

    // DECLARE THE YAHOO! VERSION OF THE WORKHORSE
    public function YGC($location)
    {
        $loc = $this->_cleanup($location);
        if (empty($loc))
        {
            $this->error = "LOCATION DATA IS EMPTY";
            return FALSE;
        }
        if (!defined('YAHOO_API')) define('YAHOO_API', 'YAHOO_API');
        $this->geocoder = 'Yahoo!';
        $yahooUrl = "http://local.yahooapis.com/MapsService/V1/geocode?&appid=" . YAHOO_API;
        $yahooUrl .= "&location=" . urlencode($loc);

        // EXECUTE YAHOO GEOCODER QUERY
        // NOTE - USE ERROR SUPPRESSION OR IT WILL BARK OUT THE YAHOO API KEY - ON FAILURE RETURNS HTTP 400 BAD REQUEST
        if ($yfp = @fopen($yahooUrl, 'r'))
        {
            $yahooResponse = '';
            while (!feof($yfp))
            {
                $yahooResponse .= fgets($yfp);
            }
            fclose($yfp);
        }
        // IF SOMETHING IS SICK AT YAHOO
        else
        {
            $this->error = "UNABLE TO OPEN $yahooUrl";
            return FALSE;
        }

        // EXAMINE THE RESULT
        if ($yahooResponse != '') // NOT EMPTY, WE GOT DATA
        {
            $ydata = new SimpleXMLElement($yahooResponse);

            // CHECK FOR ANY ERROR MESSAGE, IF NONE, EXTRACT THE DATA POINTS
            $yerror = $ydata->Message;
            if ($yerror == '')
            {
                $this->precis    = (string)$ydata->Result["precision"];
                $this->warning   = (string)$ydata->Result["warning"];
                $this->latitude  = (string)$ydata->Result->Latitude;
                $this->longitude = (string)$ydata->Result->Longitude;

                // THESE STATEMENTS CAN BE USED TO RETURN NORMALIZED ADDRESS
                $this->address   = (string)$ydata->Result->Address;
                $this->city      = (string)$ydata->Result->City;
                $this->state     = (string)$ydata->Result->State;
                $this->zip       = (string)$ydata->Result->Zip;

                // SET PRECISION TO A NUMBER VALUE
                if ($this->precis == 'zip')     { $this->precision = "5"; }
                if ($this->precis == 'street')  { $this->precision = "6"; }
                if ($this->precis == 'address') { $this->precision = "8"; }
            }
            else
            {
                $this->error = "ERROR: $yahooUrl SAYS $yerror";
                return FALSE;
            }
        }

        // NO RESULT - SOMETHING IS SICK AT YAHOO
        else
        {
            $this->error = "NO DATA RETURNED FROM $yahooUrl";
            return FALSE;
        }
        return TRUE;
    } // END function geocodeYahoo


    // DECLARE THE GOOGLE VERSION OF THE WORKHORSE
    public function GGC($location)
    {
        $loc = $this->_cleanup($location);
        if (empty($loc))
        {
            $this->error = "LOCATION DATA IS EMPTY";
            return FALSE;
        }

        if (!defined('GOOGLE_API')) define('GOOGLE_API', 'GOOGLE_API');
        $this->geocoder = 'Google';
        $googleUrl = "http://maps.google.com/maps/geo?key=" . GOOGLE_API . "&output=csv";
        $googleUrl .= "&q=" . urlencode($loc);

        // EXECUTE GOOGLE GEOCODER QUERY
        if ($gfp = @fopen($googleUrl, 'r'))
        {
            $googleResponse = '';
            while (!feof($gfp))
            {
                $googleResponse .= fgets($gfp);
            }
            fclose($gfp);
        }
        else
        {
            $this->error = "UNABLE TO OPEN $googleUrl";
            return FALSE;
        }

        // EXTRACT THE DATA FROM THE CSV STRING
        $gdata = explode(',',$googleResponse);
        if ($gdata[0] != '200') // RESPONSE CODE SHOULD BE '200' -- IF 602 - BAD ZIP CODE OR UNUSABLE ADDRESS
        {
            $this->error = "ERROR CODE {$gdata[0]} FROM $googleUrl";
            return FALSE;
        }
        $this->precision = $gdata[1]; // GEOCODE ACCURACY - ZIP CODE = 5, HIGHER NUMBERS ARE BETTER
        $this->latitude  = $gdata[2];
        $this->longitude = $gdata[3];
        return TRUE;
    } // END function geocodeGoogle

} // END class SimpleGeocoder




// UNRELATED FUNCTION TO MAKE THE OUTPUT SHOW THE PUBLIC INFORMATION ONLY
function print_rr($thing)
{
    $str = print_r($thing, TRUE);
    $arr = explode(PHP_EOL, $str);
    foreach ($arr as $ptr => $txt)
    {
        if (preg_match('/:private]/', $txt))
        {
            unset($arr[$ptr]);
        }
    }
    echo implode(PHP_EOL, $arr);
}

Open in new window

0
XzKtoCommented:
It is not simple to determine if address is real. There are no universal regular expressions or anything for addresses, you can only use some external service to check it for you.

I wrote a simple class that uses Google Maps for you that can be a good way to start(you will need Google maps API key):
<?

//This will define minimum address accuracy and address depth.
define('CheckAddress_DEFAULT_MIN_ACCURACY', 6);
define('CheckAddress_DEFAULT_MIN_ADDRESS_DEPTH', 5);

class CheckAddress {

    private $key = NULL;
    private $min_accuracy = NULL;
    private $min_address_depth = NULL;

    /**
     * Public onstructor
     * @param String $key Google maps API key
     * @param Integer $min_accuracy Minimun accuracy number
     */
    public function __construct($key, $min_accuracy=NULL, $min_address_depth=NULL) {
        $this->key = $key;
        $this->min_accuracy = $min_accuracy === NULL ? CheckAddress_DEFAULT_MIN_ACCURACY : (int) $min_accuracy; //Set minimum accuracy
        $this->min_address_depth = $min_address_depth === NULL ? CheckAddress_DEFAULT_MIN_ADDRESS_DEPTH : (int) $min_address_depth; //Set minimum address depth
    }

    /**
     * Function to set minimum address accuracy.
     * @param Integer $min_accuracy New value.
     */
    public function set_min_accuracy($min_accuracy) {
        $this->min_accuracy = (int) $min_accuracy;
    }

    /**
     * Function to set minimum address depth.
     * @param Integer $min_address_depth New value.
     */
    public function set_min_depth($min_address_depth) {
        $this->min_address_depth = (int) $min_address_depth;
    }

    /**
     * Main method - checks if address exists.
     * @param String $address_str address to check
     */
    public function check_address($address_str) {
        //Encode address to pass in url
        $address_str = urlencode($address_str);
        //Get google response for API call
        $address_data = $this->get_google_response($address_str);
        if (gettype($address_data) !== 'string' || !strlen($address_data)) {
            //Return NULL if we got bad data
            return NULL;
        }
        //Make XML object from got data
        $xml = simplexml_load_string($address_data);
        if ($xml === FALSE) {
            //Return NULL if we got invalid XML data
            return NULL;
        }
        if (!isset($xml->Response, $xml->Response->Status, $xml->Response->Status->code) || (int) $xml->Response->Status->code !== 200) {
            //Something bad happened and we didn't get response code,
            //or it was error response code
            return NULL;
        }
        if (!isset($xml->Response->Placemark, $xml->Response->Placemark->address, $xml->Response->Placemark->AddressDetails, $xml->Response->Placemark->AddressDetails['Accuracy'])) {
            //Something bad happened and we didn't get address accuracy
            return NULL;
        }
        $address_depth = substr_count($xml->Response->Placemark->address, ',') + 1;
        return ($address_depth >= $this->min_address_depth)
        &&
        ($xml->Response->Placemark->AddressDetails['Accuracy'] >= $this->min_accuracy);
    }

    private function get_google_response($address_str) {
        //API call url
        $url = "http://maps.google.com/maps/geo?q=" . $address_str . "&output=xml&key=" . $this->key;
        //Initialize curl
        $google_request = curl_init();
        //Ser basic options
        curl_setopt($google_request, CURLOPT_URL, $url);
        curl_setopt($google_request, CURLOPT_HEADER, 0); //Change this to a 1 to return headers
        curl_setopt($google_request, CURLOPT_USERAGENT, 'PHP');
        curl_setopt($google_request, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($google_request, CURLOPT_RETURNTRANSFER, 1);

        //Return got data
        return curl_exec($google_request);
    }

}

$key = "Your google maps API key.";
$address = new CheckAddress($key);
if ($address->check_address('Moskva, kulikovskaia, 7')) {
    echo 'Valid address.';
} else {
    echo 'Invalid address.';
}

Open in new window


You can play with defines, add &gl variable to Google API call to specify country etc..

You can call this script from your form to check address using AJAX. You should somehow limit this checks per user so that google wont ban you.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
umaximAuthor Commented:
i try to run your script and it give me error
CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in
0
umaximAuthor Commented:
But the safe mode is disabled
0
XzKtoCommented:
Try to comment that line, it may work without it.
0
umaximAuthor Commented:
i am trying to put 83-36 beverly road kew gardens,queens,NY,11415  and it give me always error. Do i need specified country ?
0
XzKtoCommented:
Change
define('CheckAddress_DEFAULT_MIN_ADDRESS_DEPTH', 5);
to
define('CheckAddress_DEFAULT_MIN_ADDRESS_DEPTH', 4);

Basically, this constant shous how much ',' should be in address returned by google(minimum).
0
umaximAuthor Commented:
any way it said address is not real
0
umaximAuthor Commented:
thank you it work
0
Ray PaseurCommented:
@umaxim: Why didn't you try the script I posted for you at http://#35362271 -- it was the first correct and complete answer.  Typically the first correct and complete answer should receive at least some of the points.  Please explain what was wrong with the answer, thanks.

The examples I gave you clearly demonstrated how the call to the geocoders work.  Try clicking this link.  
http://www.laprbass.com/RAY_class_SimpleGeoCoder.php?a=83-36+beverly+road+kew+gardens,queens,NY,11415

If you had told us that was the address you wanted to test with it would have been a lot easier to give you the answer.
0
umaximAuthor Commented:
Ok i try your script but i was confused in it and his one was short and beatifull. If you want i can create the same question and you post you answear and i will give you point. Am sorry if i make someting wrong but i decide his answear help me the best.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.