Link to home
Start Free TrialLog in
Avatar of umaxim
umaximFlag for United States of America

asked on

PHP

Hi does any one know how i can validate if address is real by php. I need only US address
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

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

Avatar of umaxim

ASKER

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
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

ASKER CERTIFIED SOLUTION
Avatar of XzKto
XzKto
Flag of Russian Federation image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of umaxim

ASKER

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
Avatar of umaxim

ASKER

But the safe mode is disabled
Try to comment that line, it may work without it.
Avatar of umaxim

ASKER

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 ?
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).
Avatar of umaxim

ASKER

any way it said address is not real
Avatar of umaxim

ASKER

thank you it work
@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.
Avatar of umaxim

ASKER

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.