Amazon AWS APIv4 Function

Summary

This is a very simple, procedural (non-Object Oriented Programing) function for making API calls to Amazon's Web Information Services interface. No need to over-complicate these requests with hundreds of lines of OOP code.

You need to have an account with Amazon Web Services

The Code

<?
$alexa_xml 
alexa_webstats("http://www.whatsmyip.org");
$xml simplexml_load_string($alexa_xml,"SimpleXMLElement",0,"http://awis.amazonaws.com/doc/2005-07-11");
$alexa_stats["a_rank"] = $xml->Response->UrlInfoResult->Alexa->TrafficData->Rank;
$alexa_stats["a_speed"] = $xml->Response->UrlInfoResult->Alexa->ContentData->Speed->MedianLoadTime;
$alexa_stats["a_percentile"] = $xml->Response->UrlInfoResult->Alexa->ContentData->Speed->Percentile;
$alexa_stats["a_inlinks"] = $xml->Response->UrlInfoResult->Alexa->ContentData->LinksInCount;
print_r($alexa_stats);

function 
alexa_webstats($q)
    {
    
$accessKeyId ""// You need to put your key here
    
$secretAccessKey ""// And your other key here
    
$ActionName "UrlInfo";
    
$ResponseGroupName rawurlencode("Rank,Speed,LinksInCount");
    
$ServiceHost "awis.amazonaws.com";
    
$ServiceEndpoint "awis.us-west-1.amazonaws.com";
    
$NumReturn 10;
    
$StartNum 1;
    
$ServiceURI "/api";
    
$ServiceRegion "us-west-1";
    
$ServiceName "awis";
    
$site rawurlencode($q);
    
$now time();
    
$amzDate gmdate("Ymd\THis\Z"$now);
    
$dateStamp gmdate("Ymd"$now);

    
$canonicalQuery "Action=$ActionName&Count=$NumReturn&ResponseGroup=$ResponseGroupName&Start=$StartNum&Url=$site";
    
$canonicalHeaders "host:$ServiceEndpoint\nx-amz-date:$amzDate\n";
    
$signedHeaders "host;x-amz-date";
    
$payloadHash hash("sha256""");
    
$canonicalRequest "GET\n$ServiceURI\n$canonicalQuery\n$canonicalHeaders\n$signedHeaders\n$payloadHash";
    
$algorithm "AWS4-HMAC-SHA256";
    
$credentialScope "$dateStamp/$ServiceRegion/$ServiceName/aws4_request";
    
$stringToSign "$algorithm\n$amzDate\n$credentialScope\n" hash("sha256"$canonicalRequest);
    
$kSecret "AWS4$secretAccessKey";
    
$kDate hash_hmac("sha256"$dateStamp$kSecrettrue);
    
$kRegion hash_hmac("sha256"$ServiceRegion$kDatetrue);
    
$kService hash_hmac("sha256"$ServiceName$kRegiontrue);
    
$signingKey hash_hmac("sha256""aws4_request"$kServicetrue);
    
$signature hash_hmac("sha256"$stringToSign$signingKey);
    
$authorizationHeader "$algorithm Credential=$accessKeyId/$credentialScope, SignedHeaders=$signedHeaders, Signature=$signature";
    
$url "https://$ServiceHost$ServiceURI?$canonicalQuery";

    
$ch curl_init($url);
    
curl_setopt($chCURLOPT_TIMEOUT4);
    
curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
    
curl_setopt($chCURLOPT_HTTPHEADER, array("Accept: application/xml","Content-Type: application/xml","X-Amz-Date: $amzDate","Authorization: $authorizationHeader"));
    
$result curl_exec($ch);
    }
?>