Link to home
Start Free TrialLog in
Avatar of savsoft
savsoftFlag for India

asked on

how to use Alexa Web Information Service in php

i want to use Alexa Web Information Service in php
i have acces key id and secrete key id with amazon.
i found example code from  amazon at
http://aws.amazon.com/code/AWIS/402
but it din't give any result
Then i try developer guide but didn't get any thing
Developer guide is here
http://docs.amazonwebservices.com/AlexaWebInfoService/latest/awis-dg-20050711.pdf


<?php
/**
 * Makes a request to AWIS for site info.
 */
class UrlInfo {

    protected static $ActionName        = 'UrlInfo';
    protected static $ResponseGroupName = 'Rank,ContactInfo,LinksInCount';
    protected static $ServiceHost      = 'awis.amazonaws.com';
    protected static $NumReturn         = 10;
    protected static $StartNum          = 1;
    protected static $SigVersion        = '2';
    protected static $HashAlgorithm     = 'HmacSHA256';

    public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
        $this->site = $site;
    }

    /**
     * Get site info from AWIS.
     */ 
    public function getUrlInfo() {
        $queryParams = $this->buildQueryParams();
        $sig = $this->generateSignature($queryParams);
        $url = 'http://' . self::$ServiceHost . '/?' . $queryParams . 
            '&Signature=' . $sig;
        $ret = self::makeRequest($url);
        echo "\nResults for " . $this->site .":\n\n";
        self::parseResponse($ret);
    }

    /**
     * Builds current ISO8601 timestamp.
     */
    protected static function getTimestamp() {
        return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); 
    }

    /**
     * Builds query parameters for the request to AWIS.
     * Parameter names will be in alphabetical order and
     * parameter values will be urlencoded per RFC 3986.
     * @return String query parameters for the request
     */
    protected function buildQueryParams() {
        $params = array(
            'Action'            => self::$ActionName,
            'ResponseGroup'     => self::$ResponseGroupName,
            'AWSAccessKeyId'    => $this->accessKeyId,
            'Timestamp'         => self::getTimestamp(),
            'Count'             => self::$NumReturn,
            'Start'             => self::$StartNum,
            'SignatureVersion'  => self::$SigVersion,
            'SignatureMethod'   => self::$HashAlgorithm,
            'Url'               => $this->site
        );
        ksort($params);
        $keyvalue = array();
        foreach($params as $k => $v) {
            $keyvalue[] = $k . '=' . rawurlencode($v);
        }
        return implode('&',$keyvalue);
    }

    /**
     * Makes request to AWIS
     * @param String $url   URL to make request to
     * @return String       Result of request
     */
    protected static function makeRequest($url) {
        echo "\nMaking request to:\n$url\n";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * Parses XML response from AWIS and displays selected data
     * @param String $response    xml response from AWIS
     */
    public static function parseResponse($response) {
        $xml = new SimpleXMLElement($response,null,false,
                                    'http://awis.amazonaws.com/doc/2005-07-11');
        if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count()) {
            $info = $xml->Response->UrlInfoResult->Alexa;
            $nice_array = array(
                'Phone Number'   => $info->ContactInfo->PhoneNumbers->PhoneNumber,
                'Owner Name'     => $info->ContactInfo->OwnerName,
                'Email'          => $info->ContactInfo->Email,
                'Street'         => $info->ContactInfo->PhysicalAddress->Streets->Street,
                'City'           => $info->ContactInfo->PhysicalAddress->City,
                'State'          => $info->ContactInfo->PhysicalAddress->State,
                'Postal Code'    => $info->ContactInfo->PhysicalAddress->PostalCode,
                'Country'        => $info->ContactInfo->PhysicalAddress->Country,
                'Links In Count' => $info->ContentData->LinksInCount,
                'Rank'           => $info->TrafficData->Rank
            );
        }
        foreach($nice_array as $k => $v) {
            echo $k . ': ' . $v ."\n";
        }
    }

    /**
     * Generates an HMAC signature per RFC 2104.
     *
     * @param String $url       URL to use in createing signature
     */
    protected function generateSignature($url) {
        $sign = "GET\n" . strtolower(self::$ServiceHost) . "\n/\n". $url;
        echo "String to sign: \n" . $sign . "\n";
        $sig = base64_encode(hash_hmac('sha256', $sign, $this->secretAccessKey, true));
        echo "\nSignature: " . $sig ."\n";
        return rawurlencode($sig);
    }

}

if (count($argv) < 4) {
    echo "Usage: $argv[0] ACCESS_KEY_ID SECRET_ACCESS_KEY site\n";
    exit(-1);
}
else {
    $accessKeyId = $argv[1];
    $secretAccessKey = $argv[2];
    $site = $argv[3];
}

$urlInfo = new UrlInfo($accessKeyId, $secretAccessKey, $site);
$urlInfo->getUrlInfo();

?>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

What were you expecting to get?   I copied the code posted here and installed it on my server.
http://www.laprbass.com/RAY_temp_savsoft.php

Outputs:
Usage: ACCESS_KEY_ID SECRET_ACCESS_KEY site

I think we would need to see the error messages, so that is the first change you would probably want to make.
<?php // RAY_temp_savsoft.php
/**
 * Makes a request to AWIS for site info.
 */
class UrlInfo {

    protected static $ActionName        = 'UrlInfo';
    protected static $ResponseGroupName = 'Rank,ContactInfo,LinksInCount';
    protected static $ServiceHost      = 'awis.amazonaws.com';
    protected static $NumReturn         = 10;
    protected static $StartNum          = 1;
    protected static $SigVersion        = '2';
    protected static $HashAlgorithm     = 'HmacSHA256';

    public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
        $this->site = $site;
    }

    /**
     * Get site info from AWIS.
     */ 
    public function getUrlInfo() {
        $queryParams = $this->buildQueryParams();
        $sig = $this->generateSignature($queryParams);
        $url = 'http://' . self::$ServiceHost . '/?' . $queryParams . 
            '&Signature=' . $sig;
        $ret = self::makeRequest($url);
        echo "\nResults for " . $this->site .":\n\n";
        self::parseResponse($ret);
    }

    /**
     * Builds current ISO8601 timestamp.
     */
    protected static function getTimestamp() {
        return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); 
    }

    /**
     * Builds query parameters for the request to AWIS.
     * Parameter names will be in alphabetical order and
     * parameter values will be urlencoded per RFC 3986.
     * @return String query parameters for the request
     */
    protected function buildQueryParams() {
        $params = array(
            'Action'            => self::$ActionName,
            'ResponseGroup'     => self::$ResponseGroupName,
            'AWSAccessKeyId'    => $this->accessKeyId,
            'Timestamp'         => self::getTimestamp(),
            'Count'             => self::$NumReturn,
            'Start'             => self::$StartNum,
            'SignatureVersion'  => self::$SigVersion,
            'SignatureMethod'   => self::$HashAlgorithm,
            'Url'               => $this->site
        );
        ksort($params);
        $keyvalue = array();
        foreach($params as $k => $v) {
            $keyvalue[] = $k . '=' . rawurlencode($v);
        }
        return implode('&',$keyvalue);
    }

    /**
     * Makes request to AWIS
     * @param String $url   URL to make request to
     * @return String       Result of request
     */
    protected static function makeRequest($url) {
        echo "\nMaking request to:\n$url\n";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * Parses XML response from AWIS and displays selected data
     * @param String $response    xml response from AWIS
     */
    public static function parseResponse($response) {
        $xml = new SimpleXMLElement($response,null,false,
                                    'http://awis.amazonaws.com/doc/2005-07-11');
        if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count()) {
            $info = $xml->Response->UrlInfoResult->Alexa;
            $nice_array = array(
                'Phone Number'   => $info->ContactInfo->PhoneNumbers->PhoneNumber,
                'Owner Name'     => $info->ContactInfo->OwnerName,
                'Email'          => $info->ContactInfo->Email,
                'Street'         => $info->ContactInfo->PhysicalAddress->Streets->Street,
                'City'           => $info->ContactInfo->PhysicalAddress->City,
                'State'          => $info->ContactInfo->PhysicalAddress->State,
                'Postal Code'    => $info->ContactInfo->PhysicalAddress->PostalCode,
                'Country'        => $info->ContactInfo->PhysicalAddress->Country,
                'Links In Count' => $info->ContentData->LinksInCount,
                'Rank'           => $info->TrafficData->Rank
            );
        }
        foreach($nice_array as $k => $v) {
            echo $k . ': ' . $v ."\n";
        }
    }

    /**
     * Generates an HMAC signature per RFC 2104.
     *
     * @param String $url       URL to use in createing signature
     */
    protected function generateSignature($url) {
        $sign = "GET\n" . strtolower(self::$ServiceHost) . "\n/\n". $url;
        echo "String to sign: \n" . $sign . "\n";
        $sig = base64_encode(hash_hmac('sha256', $sign, $this->secretAccessKey, true));
        echo "\nSignature: " . $sig ."\n";
        return rawurlencode($sig);
    }

}

if (count($argv) < 4) {
    echo "Usage: $argv[0] ACCESS_KEY_ID SECRET_ACCESS_KEY site\n";
    exit(-1);
}
else {
    $accessKeyId = $argv[1];
    $secretAccessKey = $argv[2];
    $site = $argv[3];
}

$urlInfo = new UrlInfo($accessKeyId, $secretAccessKey, $site);
$urlInfo->getUrlInfo();

?>

Open in new window

Adding error_reporting(E_ALL); to the script gets us this:
Notice: Undefined variable: argv in /home/websitet/public_html/RAY_temp_savsoft.php on line 126
Notice: Undefined variable: argv in /home/websitet/public_html/RAY_temp_savsoft.php on line 127
Usage: ACCESS_KEY_ID SECRET_ACCESS_KEY site

What that is telling me (along with the fact that the class has not got a named __construct() method) is that you are looking at some very old code there, perhaps written in the days of PHP4.  It appears to depend on register_globals or on register_argc_argv since it tries to use $argv instead of $_SERVER["argv"].

Another thing that makes me queasy about this script is the getTimeStamp() method.  Why would someone write a protected static function to do a one-line call to a built-in PHP function?  Code like that does not make sense!

I think to make any further progress we will need to have the authorization credentials you are using for your testing.  Please post those and show us how to call the script, so we can see it in action, print out the internal variables, etc.

Thanks, ~Ray
Avatar of savsoft

ASKER

Hi,

i am posting code with access key and secret key.
Avatar of savsoft

ASKER

code is here
<?php
/**
 * Makes a request to AWIS for site info.
 */
class UrlInfo {

    protected static $ActionName        = 'UrlInfo';
    protected static $ResponseGroupName = 'Rank,ContactInfo,LinksInCount';
    protected static $ServiceHost      = 'awis.amazonaws.com';
    protected static $NumReturn         = 10;
    protected static $StartNum          = 1;
    protected static $SigVersion        = '2';
    protected static $HashAlgorithm     = 'HmacSHA256';

    public function UrlInfo($accessKeyId, $secretAccessKey, $site) {
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
        $this->site = $site;
    }

    /**
     * Get site info from AWIS.
     */ 
    public function getUrlInfo() {
        $queryParams = $this->buildQueryParams();
        $sig = $this->generateSignature($queryParams);
        $url = 'http://' . self::$ServiceHost . '/?' . $queryParams . 
            '&Signature=' . $sig;
        $ret = self::makeRequest($url);
        echo "\nResults for " . $this->site .":\n\n";
        self::parseResponse($ret);
    }

    /**
     * Builds current ISO8601 timestamp.
     */
    protected static function getTimestamp() {
        return gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time()); 
    }

    /**
     * Builds query parameters for the request to AWIS.
     * Parameter names will be in alphabetical order and
     * parameter values will be urlencoded per RFC 3986.
     * @return String query parameters for the request
     */
    protected function buildQueryParams() {
        $params = array(
            'Action'            => self::$ActionName,
            'ResponseGroup'     => self::$ResponseGroupName,
            'AWSAccessKeyId'    => $this->accessKeyId,
            'Timestamp'         => self::getTimestamp(),
            'Count'             => self::$NumReturn,
            'Start'             => self::$StartNum,
            'SignatureVersion'  => self::$SigVersion,
            'SignatureMethod'   => self::$HashAlgorithm,
            'Url'               => $this->site
        );
        ksort($params);
        $keyvalue = array();
        foreach($params as $k => $v) {
            $keyvalue[] = $k . '=' . rawurlencode($v);
        }
        return implode('&',$keyvalue);
    }

    /**
     * Makes request to AWIS
     * @param String $url   URL to make request to
     * @return String       Result of request
     */
    protected static function makeRequest($url) {
        echo "\nMaking request to:\n$url\n";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    /**
     * Parses XML response from AWIS and displays selected data
     * @param String $response    xml response from AWIS
     */
    public static function parseResponse($response) {
        $xml = new SimpleXMLElement($response,null,false,
                                    'http://awis.amazonaws.com/doc/2005-07-11');
        if($xml->count() && $xml->Response->UrlInfoResult->Alexa->count()) {
            $info = $xml->Response->UrlInfoResult->Alexa;
            $nice_array = array(
                'Phone Number'   => $info->ContactInfo->PhoneNumbers->PhoneNumber,
                'Owner Name'     => $info->ContactInfo->OwnerName,
                'Email'          => $info->ContactInfo->Email,
                'Street'         => $info->ContactInfo->PhysicalAddress->Streets->Street,
                'City'           => $info->ContactInfo->PhysicalAddress->City,
                'State'          => $info->ContactInfo->PhysicalAddress->State,
                'Postal Code'    => $info->ContactInfo->PhysicalAddress->PostalCode,
                'Country'        => $info->ContactInfo->PhysicalAddress->Country,
                'Links In Count' => $info->ContentData->LinksInCount,
                'Rank'           => $info->TrafficData->Rank
            );
        }
        foreach($nice_array as $k => $v) {
            echo $k . ': ' . $v ."\n";
        }
    }

    /**
     * Generates an HMAC signature per RFC 2104.
     *
     * @param String $url       URL to use in createing signature
     */
    protected function generateSignature($url) {
        $sign = "GET\n" . strtolower(self::$ServiceHost) . "\n/\n". $url;
        echo "String to sign: \n" . $sign . "\n";
        $sig = base64_encode(hash_hmac('sha256', $sign, $this->secretAccessKey, true));
        echo "\nSignature: " . $sig ."\n";
        return rawurlencode($sig);
    }

}






if (count($argv) < 4) {
    echo "Usage: $argv[0] ACCESS_KEY_ID SECRET_ACCESS_KEY site\n";
    exit(-1);
}
else {
    $accessKeyId = $argv[1];
    $secretAccessKey = $argv[2];
    $site = $argv[3];
}


$accessKeyId="AKIAJUPZYCEINMRXDMZQ";
$secretAccessKey="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";
$site="google.com";

$urlInfo = new UrlInfo($accessKeyId, $secretAccessKey, $site);
$urlInfo->getUrlInfo();



?>

Open in new window

SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America 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 savsoft

ASKER

i have readme file which was attached with sample code readme.txt
ASKER CERTIFIED SOLUTION
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 savsoft

ASKER

yes, its start working

problem was defined in 2nd point that You did not sign up for the Alexa Web Information Service at
http://aws.amazon.com/awis.  (This step is separate from signing
up for Amazon Web Services.)

Actually i have account with aws.amazon.com but i didn't notice that i need separate registration for
http://aws.amazon.com/awis

Thanks Ray_Paseur,

Glad it's pointed in the right direction now.  Thanks for the points, ~Ray