<?php
$contents = file("$argv[1]");
//print_r($contents); exit;
$counts = count($contents);
/*
Please Edit by Yourself!
*/
$key = '';
$secret = '';
$aws_cf_id = '';

$request_header=array();

//Prepare header for the request
$gmt_date = gmdate('D, j M Y H:i:s \G\M\T');
//$gmt_date = 'Tue, 14 Aug 2012 07:24:10 GMT';
$reference=gmdate('YmdHis');
//Creating the signature
$value=base64_encode(hash_hmac('sha1', $gmt_date, $secret, true));

//Creating the value for the authorization header
$header_auth='AWS ' . $key . ':' . $value;

$xml_body = "<InvalidationBatch xmlns=\"http://cloudfront.amazonaws.com/doc/2012-07-01/\">
   <Paths>
      <Quantity>$counts</Quantity>
      <Items>\n";
foreach ($contents as $row) {
        $line=explode("\n", $row);
        $xml_body .= "  <Path>". $line[0] ."</Path>\n";
}
$xml_body .=     "      </Items>
   </Paths>
   <CallerReference>$reference</CallerReference>
</InvalidationBatch>\n
";

//echo $xml_body; exit;

//Prepare the header array //cloudfront.amazonaws.com
//$request_header[]='POST /2012-05-05/distribution/E1TDIAMFDUQT5Q/invalidation HTTP/1.1';
$request_header[]='POST cloudfront.amazonaws.com HTTP/1.1';
$request_header[]='Host: cloudfront.amazonaws.com';
$request_header[]='Authorization: '.$header_auth;
$request_header[]='Date: '.$gmt_date;
$request_header[]='Content-Type: '.'text/xml';
$request_header[]='Content-Length: '.strlen($xml_body);

    $cf_url="https://cloudfront.amazonaws.com/2012-07-01/distribution/$aws_cf_id/invalidation/";
        //Create the request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $cf_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $request_header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_body);

    //Execute the request
    $start = array_sum(explode(' ', microtime()));
    $result = curl_exec($ch);
    $stop = array_sum(explode(' ', microtime()));
    $totalTime = $stop - $start;

    //Check for errors
    if ( curl_errno($ch) ) {
        $result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
    } else {
        $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        switch($returnCode){
            case 404:
                $result = 'ERROR -> 404 Not Found';
                break;
            default:
                break;
        }
    }

    //Close the Request handler
    curl_close($ch);

    //Print result and the duration of execution
    echo 'Total time for request: ' . $totalTime . "\n";
    print_r($result);

    echo "\n";
    //Exit the execution
    exit(0);
?>                                                          
