AWS CloudFront with PHP

Amazon CloudFront is a web service for content delivery (CDN). It integrates with other Amazon Web Services EC2 / S3 to give developers and businesses an easy way to distribute content to end users with low latency and high data transfer speeds.

http://aws.amazon.com/cloudfront/

Digital Inspiration – Thanks to http://www.labnol.org… it always provides help for all latest technologies 🙂

You can follow basic steps here to setup CloudFront with Amazon S3 with your domain…
How to Setup Amazon S3 with CloudFront as a Content Delivery Network

You can download Cloudfront keys from AWS account
https://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key

<?php
 
error_reporting(E_ALL);

$file="svnlabs.flv"; // file on Amazon S3

function rsa_sha1_sign($policy, $private_key_filename) {
    $signature = "";

    // load the private key
    $fp = fopen($private_key_filename, "r");
    $priv_key = fread($fp, 8192);
    fclose($fp);
    $pkeyid = openssl_get_privatekey($priv_key);

    // compute signature
    openssl_sign($policy, $signature, $pkeyid);

    // free the key from memory
    openssl_free_key($pkeyid);

    return $signature;
}

function url_safe_base64_encode($value) {
    $encoded = base64_encode($value);
    // replace unsafe characters +, = and / with the safe characters -, _ and ~
    return str_replace(
        array('+', '=', '/'),
        array('-', '_', '~'),
        $encoded); 
}



function encode_query_params($stream_name) {

    return str_replace(
        array('?', '=', '&'),
        array('%3F', '%3D', '%26'),
        $stream_name);
}


/// Download from here... https://aws-portal.amazon.com/gp/aws/developer/account/index.html?action=access-key

$private_key_filename = 'pk-XXXXXXXXXXXXXXXXXXXX.pem';
$key_pair_id = 'XXXXXXXXXXXXXXXXXXXX';
$cloudfront= 'http://svnlabs.cloudfront.net/';

$file_location = "$cloudfront$file";

$expires = time() + 3;  // 3 min from now
$remote_ip = $_SERVER['REMOTE_ADDR'];

$policy = 
'{'.
    '"Statement":['.
        '{'.
            '"Resource":"'. $file_location . '",'.
            '"Condition":{'.
                '"IpAddress":{"AWS:SourceIp":"' . $remote_ip . '/32"},'.
                '"DateLessThan":{"AWS:EpochTime":' . $expires . '}'.
            '}'.
        '}'.
    ']' .
'}';

$encoded_policy = url_safe_base64_encode($policy);
 
$signature = rsa_sha1_sign($policy, $private_key_filename);
 
$encoded_signature = url_safe_base64_encode($signature);
$streamer="?Policy=$encoded_policy&Signature=$encoded_signature&Key-Pair-Id=$key_pair_id" 

?>
<html>
<head>
<title>CloudFront Implementation in PHP</title> 
</head>
<body>
<a href='<?php echo "$file_location$streamer"; ?>'><?php echo "$file_location$streamer"; ?></a> 
</body> 
</html>

A Master inspires you by his being & learning happens. 😉